Implement Automatic Deletion of Related Rows in Laravel Using Eloquent ORM
Eloquent ORM's standard delete() method deletes a single row. To extend this functionality and automatically delete related rows, utilize Eloquent events.
Problem:
When you delete a row with $user->delete(), how can you attach an automatic callback to delete related rows, like $this->photo()->delete()?
Solution:
The deleting event is triggered before the delete() method is called. By defining an event handler within the model class, you can perform cleanup tasks upon deletion.
<?php namespace App\Models; use Illuminate\Foundation\Auth\User as Authenticatable; class User extends Authenticatable { public function photos() { return $this->has_many('Photo'); } // This method is called before delete() is called protected static function booted () { static::deleting(function (User $user) { $user->photos()->delete(); }); } }
Additional Notes:
The above is the detailed content of How Can I Automatically Delete Related Rows When Deleting a Model in Laravel Eloquent?. For more information, please follow other related articles on the PHP Chinese website!