Automatically deleting related rows in Laravel (Eloquent ORM)

后端 未结 13 1913
半阙折子戏
半阙折子戏 2020-11-22 17:03

When I delete a row using this syntax:

$user->delete();

Is there a way to attach a callback of sorts, so that it would e.g. do this auto

13条回答
  •  一整个雨季
    2020-11-22 17:48

    There are 3 approaches to solving this:

    1. Using Eloquent Events On Model Boot (ref: https://laravel.com/docs/5.7/eloquent#events)

    class User extends Eloquent
    {
        public static function boot() {
            parent::boot();
    
            static::deleting(function($user) {
                 $user->photos()->delete();
            });
        }
    }
    

    2. Using Eloquent Event Observers (ref: https://laravel.com/docs/5.7/eloquent#observers)

    In your AppServiceProvider, register the observer like so:

    public function boot()
    {
        User::observe(UserObserver::class);
    }
    

    Next, add an Observer class like so:

    class UserObserver
    {
        public function deleting(User $user)
        {
             $user->photos()->delete();
        }
    }
    

    3. Using Foreign Key Constraints (ref: https://laravel.com/docs/5.7/migrations#foreign-key-constraints)

    $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    

提交回复
热议问题