laravelでのSoftDeletesを使用した時の削除者を同時にDBに保存する方法。
Controllers
1 public function destroy($user_id) 2 { 3 DB::beginTransaction(); 4 try { 5 User::where('id', $user_id)->delete(); 6 DB::commit(); 7 } catch (\PDOException $e) { 8 DB::rollBack(); 9 return false; 10 } 11 return true; 12 }
上記のコードで実装された時にはdeleted_at
には日付が入るのですが、この削除者もDBに保存したいです。
Controllers
1 public function destroy($user_id) 2 { 3 DB::beginTransaction(); 4 try { 5 User::where('id', $user_id)->update([ 6 'deleted_at' => '2020-03-10', 7 'deleted_user_id' => 1, 8 ]); 9 DB::commit(); 10 } catch (\PDOException $e) { 11 DB::rollBack(); 12 return false; 13 } 14 return true; 15 }
上記のようにはかけると思いますが、もう少し綺麗になるのかと探しています。
models
1<?php 2 3namespace App\Models; 4 5use Illuminate\Database\Eloquent\Model; 6use Illuminate\Database\Eloquent\SoftDeletes; 7 8class Calendar extends Model 9{ 10 use SoftDeletes; 11 protected $table = 'users'; 12 protected $dates = ['deleted_at']; 13} 14
Observer
Observers
1<?php 2namespace App\Observers; 3 4use Illuminate\Database\Eloquent\Model; 5 6class AuthorObserver 7{ 8 public function creating(Model $model) 9 { 10 $model-> deleted_user_id = 1; 11 } 12 13 public function updating(Model $model) 14 { 15 $model-> deleted_user_id = 1; 16 } 17 18 public function saving(Model $model) 19 { 20 $model-> deleted_user_id = 1; 21 } 22 23 public function deleting(Model $model) 24 { 25 $model-> deleted_user_id = 1; 26 } 27 28 public function restoring(Model $model) 29 { 30 $model-> deleted_user_id = 1; 31 } 32 33 public function destroy(Model $model) 34 { 35 $model-> deleted_user_id = 1; 36 } 37} 38
Traits
1<?php 2namespace App\Traits; 3 4use App\Observers\AuthorObserver; 5use Illuminate\Database\Eloquent\Model; 6 7trait AuthorObservable 8{ 9 public static function bootAuthorObservable() 10 { 11 self::observe(AuthorObserver::class); 12 } 13}
Model
1<?php 2 3namespace App\Models; 4 5use App\Traits\AuthorObservable; 6use Illuminate\Database\Eloquent\Model; 7use Illuminate\Database\Eloquent\SoftDeletes; 8 9class User extends Model 10{ 11 use AuthorObservable; 12 use SoftDeletes; 13 protected $table = 'users'; 14 protected $dates = ['deleted_at']; 15 16 public function shop() 17 { 18 return $this->belongsTo('App\Models\Shop'); 19 } 20 21 public function created_by() 22 { 23 return $this->belongsTo('App\Models\User', 'created_by'); 24 } 25 26 public function updated_by() 27 { 28 return $this->belongsTo('App\Models\User', 'updated_by'); 29 } 30 31 32} 33
Controllers
1 public function destroy($user_id) 2 { 3 DB::beginTransaction(); 4 try { 5 User::where('id', $user_id)->delete(); 6 DB::commit(); 7 } catch (\PDOException $e) { 8 DB::rollBack(); 9 return false; 10 } 11 return true; 12 }
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2020/03/10 06:34
退会済みユーザー
2020/03/10 07:04
2020/03/10 07:18
退会済みユーザー
2020/03/10 09:03
2020/03/10 12:34
退会済みユーザー
2020/03/10 13:59
2020/03/10 23:18
退会済みユーザー
2020/03/11 01:22
2020/03/11 05:57
退会済みユーザー
2020/03/11 06:05