Categories
Programming

Why your photos not deleted when you delete a user in Laravel

Ok so you have a relationship mentioned in your eloquent user model to link the photo model relationship. So in your user model class you might have something like below to define the relationship.

/**
 * Get the photos
 * @return \Illuminate\Database\Eloquent\Relations\HasMany
 */
public function photos()
{
    return $this->hasMany(Photo::class);
}

In your Photo class you might have put some code for deleting event to delete the photo files.

protected static function boot()
{
    parent::boot();

    static::deleting(function ($photo) {
        $photo->deletePhoto();
    });
}

Ok so now you can define what to do when the user is getting deleted. Here’s the catch.

If you use the relationship as a function and then call delete on the return query, it will not execute the deleting block for the photos. See following.

static::deleting(function($user) {
    $user->photos()->delete();
});

It is because the query does not identify the photo objects and only delete the records in the table.

To overcome this you have to iterate over each photo object and call delete. That way the object will execute the deleting code block in the Photo class.

static::deleting(function($user) {
    foreach($user->photos as $photo) {
        $photo->delete();
    }
});

 

 

 

 

0 0 vote
Article Rating

By Sinaru Gunawardena

Sinaru is a software developer at work and a painter in free time. He enjoys writing tech notes on his personal website. He currently lives in Dublin, Ireland.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments