Search code examples
phplaravellaravel-nova

Laravel Nova required image upload on every edit


I'm using laravel-nova and on one resource I'm using the Image field:

use Laravel\Nova\Fields\Image;

Image::make('Top Image', 'hero_image')
      ->help('Upload an image to display as hero')
      ->disk('local')
      ->maxWidth(400)
      ->prunable()
      ->rules('required')
      ->hideFromIndex(),

So far so good, but since it's required, I have to upload (the same) Image everytime I want to edit the resource which is a bit annoying and I don't want to make it not required.

So, is there a solution for this?


Solution

  • First of all, you want to make it required only on creation, so you should use ->creationRules('required') instead of ->rules('required').

    But then the issue would be the user can delete the photo, and save the resource with no image.

    To fix that, you simply have to disable the delete feature on the field with ->deletable(false).

    Image::make('Top Image', 'hero_image')
        ->help('Upload an image to display as hero')
        ->disk('local')
        ->maxWidth(400)
        ->prunable()
        ->creationRules('required')
        ->deletable(false)
        ->hideFromIndex(),
    

    This will allow you to update your resource without having to upload an image every time. And the user would only be able to replace the original image with another image.