lundi 26 mars 2018

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

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="" ></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" => "newuser@testserver.asap"
      "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" => "newuser@testserver.asap"
      "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]



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire