Laravel 5.1将中间件添加到资源路由

时间:2015-09-04 04:48:36

标签: php laravel-5.1

因此我一直在尝试将中间件与我的路由资源一起使用,并且无法使其正常工作。

这是我的路线设置:

Route::group(['prefix' => 'api','middleware' => 'locationRouteValidator'], function()
{
    Route::resource('location', 'LocationController');
});

和路线似乎设置正确:

php artisan route:list
+--------+----------+------------------------------+----------------------+-------------------------------------------------+------------------------+
| Domain | Method   | URI                          | Name                 | Action                                          | Middleware             |
+--------+----------+------------------------------+----------------------+-------------------------------------------------+------------------------+
|        | GET|HEAD | /                            |                      | Closure                                         |                        |
|        | GET|HEAD | api/location                 | api.location.index   | App\Http\Controllers\LocationController@index   | locationRouteValidator |
|        | POST     | api/location                 | api.location.store   | App\Http\Controllers\LocationController@store   | locationRouteValidator |
|        | GET|HEAD | api/location/create          | api.location.create  | App\Http\Controllers\LocationController@create  | locationRouteValidator |
|        | DELETE   | api/location/{location}      | api.location.destroy | App\Http\Controllers\LocationController@destroy | locationRouteValidator |
|        | PATCH    | api/location/{location}      |                      | App\Http\Controllers\LocationController@update  | locationRouteValidator |
|        | GET|HEAD | api/location/{location}      | api.location.show    | App\Http\Controllers\LocationController@show    | locationRouteValidator |
|        | PUT      | api/location/{location}      | api.location.update  | App\Http\Controllers\LocationController@update  | locationRouteValidator |
|        | GET|HEAD | api/location/{location}/edit | api.location.edit    | App\Http\Controllers\LocationController@edit    | locationRouteValidator |
+--------+----------+------------------------------+----------------------+-------------------------------------------------+------------------------+

所以现在我创建了中间件:

php artisan make:middleware locationRouteValidator

并保留默认代码,即:

public function handle($request, Closure $next)
{
    return $next($request);
}

只是为了测试,在我的控制器show方法中,我像这样回应传递的id:

public function show($id)
{
    //
    echo "show ".$id;
}

所以现在我希望当我访问/public/api/location/abcd时,它应该显示: show abcd或当我访问/public/api/location/1234时,它应显示show 1234,之后我打算修改中间件,只允许将数值传递到{location}

但是,如果我只使用默认的中间件代码运行,页面将返回白色而不显示任何内容。我从路径中删除了中间件,并按预期显示了文本。

我知道我可以将中间件附加到控制器上,但我想把它连接到路径中,以便我可以使用路由的组功能编写和应用一些常见的中间件,这应该是可能的,对吗? / p>

你们认为我哪里错了?提前感谢您的期待!

1 个答案:

答案 0 :(得分:1)

检查您的\ app \ http \ kernel.php文件,看看您是否已将中间件注册为路由中间件。