LoginSignup
0
0

More than 1 year has passed since last update.

【Laravel】Eloquentのdelete()メソッドで、モデルイベントが発生しない(場合がある)

Posted at

モデルの削除時に何か処理をしたい場合、下記のように実装することができます。

Laravel
class Post extends Model
{
    public static function boot()
    {
        parent::boot();

        self::deleting(function ($item) {
            // 削除時の処理
                :
                :
        });
    }
}

例えば、削除するレコードに関連した別のレコードを更新する、レコードが削除されたことを通知する(ここに実装する処理ではないかもしれませんが例えば、です)、みたいな処理が考えられますね。

ですが、下記のようなコードではイベントが発生しません。

Laravel
    Post::where('id', '<', 10)
            ->delete();
}

この挙動については Laravel のドキュメントにも記載ありました。
https://laravel.com/docs/8.x/eloquent#events

When issuing a mass update or delete query via Eloquent, the saved, updated, deleting, and deleted model events will not be dispatched for the affected models. This is because the models are never actually retrieved when performing mass updates or deletes.

Eloquentを介しての大量の更新処理、削除処理に対してモデルイベントは発生しません・・・、ということですね。

解決策としては、

1つひとつ削除するか、

Laravel
    Post::where('id', '<', 10)
            ->get()
            ->each(function($item) {
                $item->delete();
            });
}

destory()メソッドを使用します。

Laravel
    $ids = Post::where('id', '<', 10)
            ->get()
            ->pluck('id')
            ->toArray();
    Post::destroy($ids);
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0