laravel eloquent delete relationships

Submitted by dickyeka - 2 months ago

Automatically deleting related rows in Laravel (Eloquent ORM)

class User extends Eloquent
{

    public function photos()
    {
        return $this->has_many('Photo');
    }

    public function delete()
    {
        // delete all related photos 
        $this->photos()->delete();
        // as suggested by Dirk in comment,
        // it's an uglier alternative, but faster
        // Photo::where("user_id", $this->id)->delete()

        // delete the user
        return parent::delete();
    }
}
comments powered by Disqus

Ads cover the costs of maintaining Laravel-tricks