Ying
Ying

Reputation: 1422

Errors when deleting images in Laravel when no record found

I want to delete some user, and if that user have an avatar i want to remove the avatar either. so i do like this :

public function destroy($id)
    {
        $user = User::findOrFail($id);
        if ($user && $user->profile->avatar){
            Storage::delete($user->profile->avatar);
        }

        User::destroy($id);
        return back();
    }

but when i do this it give me an error like this when user doesn't have any record in avatar tables:

"Trying to get property of non-object"

so what make me get this errors and how can i fix it. thanks.

Upvotes: 1

Views: 55

Answers (1)

Chay22
Chay22

Reputation: 2894

You need to check if user has profile, first.

if ($user && $user->profile && $user->profile->avatar){
    Storage::delete($user->profile->avatar);
}

Anyways, doing this at model level will make your controller a little bit cleaner. Example for attaching a listener through the model directly.

class User extends Model
{
    protected static function boot()
    {
        parent::boot();

        static::deleting(function ($instance) {
            if ($instance->profile && $instance->profile->avatar) {
                \Storage::delete($instance->profile->avatar);
            }
        });
    }
}

Upvotes: 2

Related Questions