Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass a custom message (or any other data) to Laravel 404.blade.php

I am using Laravel 5, and I have created a file 404.blade.php in

views/errors/404.blade.php

This file gets rendered each time I call:

abort(404); // alias of App::abort(404);

How can I pass a custom message? Something like this in 404.blade.php

Sorry, {{ $message }}

Filled by (example):

abort(404, 'My custom message'); 

or

abort(404, array(
    'message' => 'My custom message'
));

In Laravel 4 one could use App::missing:

App::missing(function($exception)
{
    $message = $exception->getMessage();
    $data = array('message', $message);
    return Response::view('errors.404', $data, 404);
});
like image 672
giò Avatar asked Mar 20 '15 09:03

giò


2 Answers

(Note: copied from my answer here.)

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 67
DisgruntledGoat Avatar answered Nov 01 '22 10:11

DisgruntledGoat


Extend Laravel's Exception Handler, Illuminate\Foundation\Exceptions\Handler, and override renderHttpException(Symfony\Component\HttpKernel\Exception\HttpException $e) method with your own.

If you haven't run php artisan fresh, it will be easy for you. Just edit app/Exceptions/Handler.php, or create a new file.

Handler.php

<?php namespace App\Exceptions;

use Exception;
use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;

use Symfony\Component\HttpKernel\Exception\HttpException;

class Handler extends ExceptionHandler {

  // ...

  protected function renderHttpException(HttpException $e) {
    $status = $e->getStatusCode();

    if (view()->exists("errors.{$status}")) {
      return response()->view("errors.{$status}", compact('e'), $status);
    }
    else {
      return (new SymfonyDisplayer(config('app.debug')))->createResponse($e);
    }
  }

}

And then, use $e variable in your 404.blade.php.

i.e.

abort(404, 'Something not found');

and in your 404.blade.php

{{ $e->getMessage() }}

For other useful methods like getStatusCode(), refer Symfony\Component\HttpKernel\Exception

like image 42
Harsh Vakharia Avatar answered Nov 01 '22 10:11

Harsh Vakharia