Help us understand the problem. What is going on with this article?

Laravel5でModelイベントのハンドラを登録する

More than 5 years have passed since last update.

あるModelのアイテムを削除したときに関連Modelも削除したり、ストレージのデータを削除したりしたいことがある。

Laravel5のModelには以下のようにイベントが定義されている。

vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php
    public function getObservableEvents()
    {
        return array_merge(
            array(
                'creating', 'created', 'updating', 'updated',
                'deleting', 'deleted', 'saving', 'saved',
                'restoring', 'restored',
            ),
            $this->observables
        );
    }

それぞれのイベントにハンドラを登録するときは以下のように各モデルのbootメソッドで実装。

app/Models/Sample.php
class Sample extends Model
{
    protected $table = 'samples';

    protected static function boot()
    {
        parent::boot();

        self::updating(function($sample){
            return $sample->onUpdatingHandler();

        });
        self::deleted(function($sample){
            $sample->onDeletedHandler();
        });
    }

    private function onUpdatingHandler()
    {
        //update時刻を記録したり何かする
        return true; //キャンセルしたいときはfalseを返す
    }

    private function onDeletedHandler()
    {
        //ストレージデータを削除したり関連Modelを削除したりする
    }
}

updatingやdeletingなどのing系イベントはfalseを返すとキャンセルされる。

vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php
            if ($this->fireModelEvent('deleting') === false) return false;
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした