8

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?

ST80
  • 3,565
  • 16
  • 64
  • 124
  • Either send the uploaded image along to your front-end so it will get uploaded (and handled and saved, and this is probably not what you want) again every time, or don't set it as required I guess? – Loek Jul 04 '19 at 14:49

3 Answers3

11

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.

Chin Leung
  • 14,621
  • 3
  • 34
  • 58
  • Thanks, that worked for me :-) I was not aware of the method `creationRules('required)` - is that in the documentation? Anyway, thanks again! – ST80 Jul 04 '19 at 21:37
  • @ST80 No problem! And yes the creationRules should be in the docs :) – Chin Leung Jul 05 '19 at 00:25
1

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.

HAYTHEM
  • 71
  • 1
  • 5
0

Another cause can be a mixed content error. In my case I missconfigured the APP_URL with http instead of https and that was preventing the image from being loaded in the edit view.

vguerrero
  • 898
  • 11
  • 13