Home > Backend Development > PHP Tutorial > How to Automatically Delete Related Rows When Deleting a Model in Laravel Eloquent?

How to Automatically Delete Related Rows When Deleting a Model in Laravel Eloquent?

Patricia Arquette
Release: 2024-12-10 17:13:16
Original
248 people have browsed it

How to Automatically Delete Related Rows When Deleting a Model in Laravel Eloquent?

Automatically Deleting Related Rows in Laravel (Eloquent ORM)

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:

Custom Model Event Handler

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
        });
    }
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template