Pass a custom message (or any other data) to Larav

2020-03-08 08:07发布

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);
});

3条回答
叼着烟拽天下
2楼-- · 2020-03-08 08:48

How about sharing a variable globally?

 view()->share('message', 'llnk has gone away');
 // or using the facade
 View::share('message', 'llnk has gone away badly');

Just make sure in the template to fallback to a default in case you forget to set it.

See sharing data with views: http://laravel.com/docs/5.0/views

查看更多
冷血范
3楼-- · 2020-03-08 08:59

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

查看更多
太酷不给撩
4楼-- · 2020-03-08 09:00

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

查看更多
登录 后发表回答