Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 4 - Handling 404s With Custom Messages

According to Laravel 4 docs I can throw a 404 with a custom response:

App::abort(404, 'My Message');

I can then handle all of my 404s with a custom page:

App::missing(function($exception)
{
    return Response::view('errors.missing', array(), 404);
});

How can I pass 'My Message' through to the view in the same way that the generic Laravel error page does.

Thanks!

like image 514
Luke Joyce Avatar asked Apr 11 '14 21:04

Luke Joyce


2 Answers

You can catch your message through the Exception parameter

App::missing(function($exception)
{
    $message = $exception->getMessage();
    $data = array('message', $message);
    return Response::view('errors.missing', $data, 404);
});

Note: The code can be reduced, I wrote it like this for the sake of clarity.

like image 50
Rubens Mariuzzo Avatar answered Oct 18 '22 16:10

Rubens Mariuzzo


In Laravel 5, you can provide Blade views for each response code in the /resources/views/errors directory. For example a 404 error will use /resources/views/errors/404.blade.php.

What's not mentioned in the manual is that inside the view you have access to the $exception object. So you can use {{ $exception->getMessage() }} to get the message you passed into abort().

like image 39
DisgruntledGoat Avatar answered Oct 18 '22 15:10

DisgruntledGoat