lundi 6 février 2017

Apply "exists" validation for optional field in Laravel

I am working on a project in Laravel 5.4 and i want to do a "exists" validation rule on two optional fields (only when a value is supplied).

I have tried the following:

// Define validation rules
$validator = Validator::make($request->all(), [
    'user_group_id' => 'sometimes|exists:groups,id',
    'user_organisation_id' => 'sometimes|exists:organisations,id',
    // my other required fields here...
]);

// Validate store request
if ($validator->fails())
    return redirect()
        ->back()
        ->withErrors($validator)
        ->withInput();

In my application, user's will not always belong to an group or an organisation. So, when I submit my form without selecting a group/organisation, I expected the validation to not execute, however it is - I am getting the following errors:

The selected user group id is invalid.
The selected user organisation id is invalid.

How do you make the "exists" validation rule to apply, only when a value is supplied? using the "sometimes" flag doesn't seem to be working.


Do I need to do something like this?:

// Define validation rules
$rules = [
    // my normal required validation fields here
];
if (!empty($request->user_group)) $rules[] = ['user_group' => 'exists:groups,id'];
if (!empty($request->user_organisation)) $rules[] = ['user_organisation' => 'exists:organisations,id'];
$validator = Validator::make($request->all(), $rules);



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2kdmTPv
via IFTTT

Aucun commentaire:

Enregistrer un commentaire