Areg
Areg

Reputation: 1485

Laravel can't catch exception and redirect with error message

I am trying to catch PostTooLargeException error and redirect it with error message. Here's the handler which I wrote

if ($exception instanceof \Illuminate\Http\Exceptions\PostTooLargeException) {
   return redirect()->back()->withErrors(['msg', 'Post is too large']);
}

My create page has function to check for errors and it works when im testing on controller and through routes.

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

The redirect works however the i can't get the error message and it wont display anything. Am i missing something?

Update The post below helped me but there was another problem.And that problem was php.ini post_max_size, as i increased it everything started to work. Combined with the code below of course.

Upvotes: 3

Views: 5501

Answers (2)

Mihir Bhende
Mihir Bhende

Reputation: 9055

You can add your redirect handler inside render method of app/Exceptions/Handler.php like below :

/**
 * Render an exception into an HTTP response.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Exception  $exception
 * @return \Illuminate\Http\Response
 */
public function render($request, Exception $exception)
{
    if ($exception instanceof \Illuminate\Http\Exceptions\PostTooLargeException) {

       return \Illuminate\Support\Facades\Redirect::back()->withErrors(['msg' => 'The Message']);
    }

    return parent::render($request, $exception);
}

Then, it will send you the errors in flash session to be shown on frontend.

Upvotes: 3

balistikbill
balistikbill

Reputation: 96

I think you are trying to use 'msg' as the key for 'Post is too large', and if that's the case it should be an associative array.

->withErrors(['msg' => 'Post is too large'])

But, even with the code you have it should be displaying an error for 'msg' and 'Post is too large' in your ul element. So you would have 2 list items within that container. Not seeing anything technically wrong with what you shared to where you would see no errors on the redirect.

Upvotes: 1

Related Questions