LaraBABA's avatar

Images on edit - Best way of validating

Hello,

I would like to know what is the best way to go when you want the "required" only to be added when no images are found in the database. This is for an edit crud. The image has already been uploaded but if I click on "Update" the error shows that the image is missing because it is checking the "required" parameter from the request.

        $validator = Validator::make(
            $request->all(), [
            'name' => 'required|string|min:2|max:64',
            'landing_url' => 'url|max:255',
            'sponsor' => 'requiredimage|mimes:jpeg,bmp,png,jpg|max:10240',  <-----
            'isactivated' => 'required|integer'],
            $messages = [
                'sponsor.required' => 'You must upload an image!',
                'sponsor.max' => 'Sorry but we do not allow images bigger than 10MB!']
        );

I could do it by first checking with a DB query to see if an image if present for this id but I am wondering if there is quicker way to do this.

I looked at the doc here: https://laravel.com/docs/5.6/validation#rule-exists

There is "'state' => 'exists:states'" But in my case I would like to check if the entry is "empty" (missing) from the db entry, I cannot find anything in the doc for it.

Thank you.

0 likes
3 replies
StephenLake's avatar

Specifying A Custom Column Name

https://laravel.com/docs/5.7/validation#rule-exists

use Illuminate\Validation\Rule;

Validator::make(request()->all(), [
    'name' => 'required|string|min:2|max:64',
    'landing_url' => 'url|max:255',
    'sponsor' => 'requiredimage|mimes:jpeg,bmp,png,jpg|max:10240',
    'isactivated' => 'required|integer'
    'state' => [
        'required', Rule::exists('states')->where(function ($query) {
            $query->whereNull('your-empty-column');
        }),
    ],
]);
1 like
Snapey's avatar

Different rules for create versus update?

If not required when there is one, presumably it was required when created, therefore on update it can be nullable

Please or to participate in this conversation.