Skip to content
Advertisement

How to set validation as optional in Laravel

I want to make roles to be available only for admin can select roles for users and while user wants to edit the profile information can only see his roles but can’t edit his role how to make it roles field to be locked for users Following code :

<div class="form-group"> 
{{ Form::label('role', 'Roles', array('class' => 'control-label mb-1')) }} <br/> 
{{ Form::select('roles[]',$roles,$selectedRoles,['class'=>'myselect','data-placeholder'=>'Select role(s)', 'multiple'] ) }} 
</div>

Advertisement

Answer

You may use the following

use IlluminateValidationRule;
//..

if(!$request->filled('roles')) {
   $request->merge(['roles' => []]);
}

$this->validate($request,[
    'name' => 'required',
    'email' => 'required|email', //'required|email|unique:users,email',
    'password' => [ 'string', 'min:8'],
    'roles' => 'nullable|array', 
    'roles.*' => [Rule::requiredIf($request->filled('roles')), 'exists:roles,id'],  
],[
    'name.required' => "Name field is required",
    'email.required' => "Email Field is Required",

    'email.email' => "Invalid Email Format ",

    'password.min' => "The Password Must be at Least 8 Characters or More",
    'roles.*' => "The Role is Required",
]);

//... 
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement