简体   繁体   中英

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?

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.

I sorted it out this way, I try to find if I already got the image saved on my model first then determine if I want to require it or not.

$imageRules =  $this->company_logo ? 'sometimes' : 'required';
    return [
        Image::make('Shop Logo', 'company_logo')
            ->disk('images')
           ->rules($imageRules, 'mimes:png')
            ->disableDownload()->deletable(false),

I hope this can help others.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM