Search code examples
laravel-nova

Ho to show default avatar when avatar field is empty or file not found?


In a Laravel 10 / Nova 4.27 app, I have an avatar field defined in the User resource:

Image::make(__('Avatar'), 'avatar')
    ->disk('local')
    ->path('public/avatars')
    ->prunable()
    ->deletable(true),

How can I display a default avatar located in public/img when the avatar field is empty or the file is not found?


Solution

  • Try using the resolveUsing() method

    Image::make(__('Avatar'), 'avatar')
        ->disk('local')
        ->path('public/avatars')
        ->prunable()
        ->deletable(true)
        ->resolveUsing(function ($value) {
            // Check if the avatar exists
            if ($value && Storage::disk('local')->exists("public/avatars/{$value}")) {
                return "avatars/{$value}";
            }
    
            // Return the default image if the avatar is missing
            return 'avatars/default.jpg';
       }),
    

    This can also be done with Laravel Nova's built-in avatar field: Laravel\Nova\Fields\Avatar