In Laravel's Eloquent ORM, when deleting a record using $user->delete();, you may want to automatically delete related rows, such as $this->photo()->delete(). This can be achieved by utilizing the deleting event in your model class.
To set up the event handler, follow these steps:
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 calls this $user->photos()->delete(); // perform additional cleanup if necessary }); } }
By defining the deleting event handler, every time a User model is deleted, the related Photo models will also be automatically deleted. To ensure referential integrity, it's recommended to wrap the deletion process within a transaction.
The above is the detailed content of How to Automatically Delete Related Rows When Deleting a Model in Laravel Eloquent?. For more information, please follow other related articles on the PHP Chinese website!