mercredi 25 décembre 2019

Laravel redirect with input and with errors not working

I am having issues with getting the ->withInput() and ->withErrors() to work so that upon a validation failure I can retrieve these in the blade.

This is what I have in the controller:

$rules = array(
   'mobile' => 'required'
);

$validator = Validator::make($request->all(), $rules);

if ($validator->fails()) {
    $fieldsWithErrorMessagesArray = $validator->messages();
    $fieldsWithErrorMessagesArray = $fieldsWithErrorMessagesArray->messages();

    $formattedErrorArray = array();
    foreach ($fieldsWithErrorMessagesArray as $key => $error) {
       $formattedErrorArray[$key] = $error[0];
    }

    return redirect()->back()->withInput()->withErrors($formattedErrorArray);
}

However in the blade when var_dump the $errors, I am getting this:

object(Illuminate\Support\ViewErrorBag)#267 (1) { ["bags":protected]=> array(0) { } }

If I were to dd($fieldsWithErrorMessagesArray), it will give me:

array:7 [▼
  "mobile" => array:1 [▼
       0 => "The mobile field is required."
  ]
]

I also tried this way :

$test = array(
            'mobile' => 'No jobs found. Please try searching with different criteria'
        );

return redirect()->back()->withInput()->withErrors($test);

This worked and I am not sure why the other one doesn't work. With this test array the blade file looks like this :

object(Illuminate\Support\ViewErrorBag)#264 (1) { ["bags":protected]=> array(1) { ["default"]=> object(Illuminate\Support\MessageBag)#265 (2) { ["messages":protected]=> array(2) { ["mobile"]=> array(1) { [0]=> string(59) "No jobs found. Please try searching with different criteria" }} ["format":protected]=> string(8) ":message" } } }


via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire