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

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

Barbara Streisand
Release: 2024-12-14 11:05:10
Original
423 people have browsed it

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

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

Additional Notes:

  • Using the booted method to declare event handlers is recommended.
  • Consider wrapping the cleanup actions inside a transaction to maintain referential integrity.

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!

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