Search code examples
phplaraveleloquenteloquent-relationship

Automatically deleting related rows in Laravel (Eloquent ORM)


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 automatically:

$this->photo()->delete();

Preferably inside the model-class.


Solution

  • I believe this is a perfect use-case for Eloquent events. You can use the "deleting" event to do the cleanup:

    <?php
    
    namespace App\Models;
    
    use Illuminate\Foundation\Auth\User as Authenticatable;
    
    class User extends Authenticatable
    {
        public function photos()
        {
            return $this->has_many('Photo');
        }
        
        // this is a recommended way to declare event handlers
        protected static function booted () {
            static::deleting(function(User $user) { // before delete() method call this
                 $user->photos()->delete();
                 // do the rest of the cleanup...
            });
        }
    }
    

    You should probably also put the whole thing inside a transaction, to ensure the referential integrity..