Fnr
Fnr

Reputation: 2274

Laravel - Controller not setting some variables when return using Redirect::to

In my controller, I validate the input fields and if any validation fails I want to return back to the form and refill the previous values that the user was inputing (if there is any other easier way instead this please tell me). But here is what I'm doing:

Controller.php:

public function store(Request $request, AnexoController $anexoController)
{
    $validator = Validator::make(
        $request->all(), 
        $rules, 
        $messages
    );

    if($validator->fails())
    {
        return Redirect::to($request->headers->get('referer'))
         ->withErrors($validator)
         ->withReq($request->all());
    }

    // continues the function...
}

At the view.blade.php:

<input type="text" 
    maxlength="256" 
    id="text-input" 
    name="id" 
    placeholder="Código" 
    class="form-control" 
    @if(isset($req)) value="{{$req->id}}"
    @else value="$REQ VARIABLE NOT SET"
    @endif
    required>

And when I test it, the field id value is set to "$REQ VARIABLE NOT SET" but $errors from $validator variable is set. So, why isn't the variable $req being set in this context? Thanks in advance.

Upvotes: 0

Views: 116

Answers (1)

Aditya Thakur
Aditya Thakur

Reputation: 2610

Use this

$request->validate([
  //rules
]);

It will automatically return to form page with all the errors and inputs,

In your form you'll neet do add a helper in value of inputs for old inputs

<input type="text" value={{ old('email')}} name="email">

see https://laravel.com/docs/5.8/validation & https://laravel.com/docs/5.8/helpers

Upvotes: 1

Related Questions