Laravel 5:在视图中从Exception获取自定义消息

时间:2017-12-20 08:06:14

标签: laravel laravel-5

在Laravel 5中我的代码为:

$data = Contents::whereSlug($content)->orWhere('id', '=', $content)->first();

可能会返回null。我想用自定义消息管理它并在视图中显示。例如:

Route::get('/showContent/{content}', function ($content) {
    $data = Contents::whereSlug($content)->orWhere('id', '=', $content)->first();
    if ($data == null) {
        abort(404, 'content not found');
    }
    $serverInformation = ServerInformation::find(1);
    return view('layouts.frontend.pages.showContent', compact(
        'data',
        'serverInformation'
    ));
});

我在errors上有resources/views/missing.blade.php个文件夹,现在我希望此代码在content not found上显示此消息:

<!DOCTYPE html>
<html>
<head>

</head>
<body>
<h2>{{ $exception->getMessage() }}</h2></body>
</html>

不幸的是我收到了这个错误:

Undefined variable: exception (View: /Applications/XAMPP/xamppfiles/htdocs/alachiqServer/resources/views/errors/missing.blade.php
render文件上

Handler.php

public function render($request, Exception $e)
{
    if ($e instanceof ModelNotFoundException or $e instanceof NotFoundHttpException) {
        if ($request->ajax()) {
            return response()->json(['error' => 'Not Found'], 404);
        }
        return response()->view('errors.missing', [], 404);
    }

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

我该如何解决这个问题? resource

1 个答案:

答案 0 :(得分:0)

问题解决了,我的更新代码:

return response()->view('errors.missing', compact('exception'), 404);