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()

    static::deleting(function ($photo) {

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) {

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) {





0 0 votes
Article Rating





Leave a Reply

Your email address will not be published. Required fields are marked *

Would love your thoughts, please comment.x