Suhadak Akbar
Suhadak Akbar

Reputation: 155

Redirect with session from FormRequest Laravel

I was performing validation inside controller, and from there I can return messages through the session.

return redirect()->back()
            ->withErrors($validator)
            ->with([
                'editModal' => 'editModal',
                'msg'       => $msg
            ]);

Then, I tried using FormRequest in Laravel. This FormRequest works, but I want to send some data with session if validation is failed. But I can not find a way to do this. I can send messages using $validator->errors()->add but is there a way to send a message through session the same way I used with() in the controller?

Upvotes: 2

Views: 1426

Answers (3)

Suhadak Akbar
Suhadak Akbar

Reputation: 155

After spending my times, I found a way to send message through session. Just add this function on FormRequest class you use.

protected function failedValidation(Validator $validator)
{
    return redirect()->back()
        ->withErrors($validator)
        ->with([ //these are my messages
            'editModal' => 'editModal',
            'msg'       => $this->input()
        ]);
}

Don't forget to use Illuminate\Contracts\Validation\Validator;

Upvotes: 1

miken32
miken32

Reputation: 42699

The FormRequest::failedValidation() method throws an instance of \Illuminate\Validation\ValidationException to indicate a validation failure.

There are two methods in Illuminate\Foundation\Exceptions\Handler that deal with building the response for these exceptions. You'll need to override these two methods, invalid() and invalidJson(), to include your session data.

These overrides belong in your app's exception handler, found at app/Exception/Handler.php and should look something like this:

protected function invalid($request, ValidationException $exception)
{
    return redirect($exception->redirectTo ?? url()->previous())
                ->withInput(Arr::except($request->input(), $this->dontFlash))
                ->withErrors($exception->errors(), $exception->errorBag)
                ->with([
                    'editModal' => 'editModal',
                    'msg'       => $msg
                ]);
}

protected function invalidJson($request, ValidationException $exception)
{
    return response()
        ->json([
            'message' => $exception->getMessage(),
            'errors' => $exception->errors(),
        ], $exception->status)
        ->with([
            'editModal' => 'editModal',
            'msg'       => $msg
        ]);

}

Upvotes: 1

Poldo
Poldo

Reputation: 1932

You can add custom error in validators error

$validator->errors()->add('editModal', 'editModal');
$validator->errors()->add('msg', $msg);
return redirect()->back()->withErrors($validator);

in your blade

@if($errors->any())
 <h4>{{$errors->first()}}</h4>
@endif

Upvotes: 1

Related Questions