The requirement was to update user roles. The role can be empty(left blank), one, or more than one as provided in the form field roles[]
.
Here is the view form:
@foreach ($roles as $role)
<div class="checkbox">
<label><input name="roles[]" type="checkbox" value="{{$role->id}}" {{ $user->roles->contains($role->id) ? 'checked' : '' }}>{{$role->name}}</label>
</div>
@endforeach
The condition inside UserController::update() is:
if ($request->roles) {
// update user roles
}
Everything works fine except for one case. Sometimes the user has to stay without any role.
if($request->roles)
, isset($request->roles)
, and !empty($request->roles)
.. are all giving the same old fashioned reply(null
, ''
, true/flase
).
Case: when there is one or more role(s) assigned:
+request: ParameterBag {#41 ▼
#parameters: array:6 [▼
"_method" => "PUT"
"_token" => "a8oIPQFBMbhjanikX8v83qeOcfRE0N4UKTcTQDig"
"name" => "New User Name"
"email" => "[email protected]"
"password" => ""
"roles" => array:2 [▼
0 => "2"
1 => "3"
]
]
}
Case: when there no role assigned OR need to remove(detach) the previously assigned role:
+request: ParameterBag {#41 ▼
#parameters: array:5 [▼
"_method" => "PUT"
"_token" => "a8oIPQFBMbhjanikX8v83qeOcfRE0N4UKTcTQDig"
"name" => "New User Name"
"email" => "[email protected]"
"password" => ""
]
}
So the question (requirement) is:
How to differentiate when the field value of an HTML Post form has been submitted as empty(unchecked here) or if there was no such a field in the view form?
Is there an eloquent* way in Laravel to find/list the form fileds from the Request
object?
[PS: Trying another hidden field or do some frontend jQuery will not be appreciated]
$request->has('roles')
is giving the same result! – Holsisset($request->roles)
says true or false, how do I know when there was a field but still left empty? @ashokpoudel – Hols$_POST
contains all form fields. There is a chance that:$request->filled('roles')
may help for 5.5+ users but not others. Another logic (i.e, by taking the input value as an array) helped to to solve my custom requirement and still the question remains. – Hols