What is the Laravel way to check if the POST Request has a field left empty?

Eazy Sam picture Eazy Sam · Mar 26, 2018 · Viewed 17.7k times · Source

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]

Answer

Asur picture Asur · Mar 26, 2018

You can use the laravel request methods has() or filled(), has checks if the parameter is present and filled checks it's present and filled:

if ($request->has('roles')) {
    //
}

or

if ($request->filled('roles')) {
    //
}

Check Laravel documentation for further details on retrieving input from the request object.

EDIT

Since you are using Laravel 5.2 the following rules apply:

  • The has() method checks the parameter is present and filled.
  • The exists() method checks the parameted is present.

Check the code on the repo for more information.