Luke Joyce
Luke Joyce

Reputation: 88

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!

Upvotes: 5

Views: 2535

Answers (2)

DisgruntledGoat
DisgruntledGoat

Reputation: 72510

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().

Upvotes: 4

Rubens Mariuzzo
Rubens Mariuzzo

Reputation: 29231

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.

Upvotes: 5

Related Questions