自定义“未找到" Laravel的路由“显式绑定"的行为 [英] Customizing The "Not Found" Behavior of Laravel's Routing "Explicit Binding"
问题描述
以下是文档: https://laravel.com/docs/5.2/routing#route-model-binding
路线:
Route::group(['prefix' => 'u'], function () {
Route::post('create', ['as' => 'createUser', 'uses' => 'UserController@create']);
Route::get('{uuid}', ['as' => 'userDashboard', 'uses' => 'UserController@dashboard']);
});
UserController.php:
The UserController.php:
public function dashboard(User $uuid)
{
return View::make('user.dashboard');
}
每当在数据库中找不到用户时,它都会引发以下两个异常:
Whenever the User isn't found in the database it throws these two exceptions:
2/2
NotFoundHttpException in Handler.php line 103:
No query results for model [App\User].
1/2
ModelNotFoundException in Builder.php line 303:
No query results for model [App\User].
如何自定义错误?我想重定向到createUser
路由.该文档指示将Closure
作为第三个参数传递,但是我不知道如何使用当前代码执行该操作.
How do I customize the error? I want to redirect to the createUser
route. The documentation instructs to pass a Closure
as a third argument but I don't know how to do that with my current code.
编辑1
这是到目前为止我没有成功尝试过的事情:
This is what I've tried so far without success:
Route::model('{uuid}', ['as' => 'userDashboard', 'uses' => 'UserController@dashboard'], function () {
App::abort(403, 'Test.');
});
Route::get('{uuid}', ['as' => 'userDashboard', 'uses' => 'UserController@dashboard'], function () {
App::abort(403, 'Test.');
});
推荐答案
这实际上非常简单.由于没有一个答案能真正给出确切的答案,因此我自己回答.
This is actually very simple. As none of the answers really give a definite answer I am answering it myself.
在文件RouteServiceController.php
的boot
函数中添加以下内容:
In the file RouteServiceController.php
's boot
function add the following:
$router->model('advertiser', 'App\Advertiser', function () {
throw new AdvertiserNotFoundException;
});
然后在App\Exceptions
中创建一个新的空类,称为(c5):
Then create a new empty class in App\Exceptions
called (in this case) AdvertiserNotFoundException.php
:
<?php
namespace App\Exceptions;
use Exception;
class AdvertiserNotFoundException extends Exception
{
}
最后要做的是像这样在Handler.php
的render
函数(App\Exception
)中捕获异常:
The last thing to do is to catch the exception in the Handler.php
's render
function (App\Exception
) like so:
public function render($request, Exception $e)
{
switch ($e)
{
case ($e instanceof AdvertiserNotFoundException):
//Implement your behavior here (redirect, etc...)
}
return parent::render($request, $e);
}
就是这样! :)
这篇关于自定义“未找到" Laravel的路由“显式绑定"的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!