Gabriel Edu
Gabriel Edu

Reputation: 678

Using the redirect method, errors are not sent to view

When I use return view('login')->withErrors($validator->errors());, I get the errors returned if any. Now, if I use the Redirect method/class, it doesn't return the data.

I need to use redirect. I tested it in several ways, going through the different errors, but nothing works. I've read documentation, blogs and everything I do doesn't work.

I already tried return Redirect::back()->withErrors(['msg' => 'The Message']); and in the blade `{{ session()->get('msg') }}, but nothing .

I need some help as I have tried many things and nothing works.

Controller:

public function checkUserExists(Request $request)
{
        $email = $request->input('email');

        $validator = Validator::make(
            $request->all(), 
            [
                'email' => ['required', 'max:255', 'string', 'email'],
                'g-recaptcha-response' => ['required', new RecaptchaRule],
            ],
            $this->messages
        );

        if ($validator->fails()) {
            // return view('login')->withErrors($validator->errors());

            // return Redirect::back()->withErrors(['msg' => 'The Message']);
            return Redirect::route('login')->withErrors($validator->errors());
            // return Redirect::route('login')->withErrors($validator);
            // return redirect()->back()->withErrors($validator->errors());
            // return Redirect::back()->withErrors($validator)->withInput();
        }
   ...

}

At the moment my bucket is just with this:

{{-- Errors --}}
@if ($errors->any())
    <div class="alert alert-danger" role="alert">
      <ul>
        @foreach ($errors->all() as $key => $error)
          <li>
           {{ $error }}
          </li>
        @endforeach
      </ul>
    </div>
@endif

Version of Laravel: "laravel/framework": "^7.29",

Upvotes: 5

Views: 74

Answers (1)

Amir Sadeghi
Amir Sadeghi

Reputation: 11

try this code to pass the errors back to the view:

public function checkUserExists(Request $request)
{
    $email = $request->input('email');

    $validator = Validator::make(
        $request->all(), 
        [
            'email' => ['required', 'max:255', 'string', 'email'],
            'g-recaptcha-response' => ['required', new RecaptchaRule],
        ],
        $this->messages
    );

    if ($validator->fails()) {
        return redirect()->back()->withErrors($validator)->withInput();
    }

   ...
}

& in your view, you can access the errors using with:

{{-- Errors --}}
@if ($errors->any())
    <div class="alert alert-danger" role="alert">
      <ul>
        @foreach ($errors->all() as $error)
          <li>{{ $error }}</li>
        @endforeach
      </ul>
    </div>
@endif

this should work if your view is correct and you are using the correct path to your view in your redirect()->back() method

Upvotes: 1

Related Questions