0
因此,我一直在嘗試將中間件與我的路由資源配合使用,並且無法使其工作。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\[email protected] | locationRouteValidator |
| | POST | api/location | api.location.store | App\Http\Controllers\[email protected] | locationRouteValidator |
| | GET|HEAD | api/location/create | api.location.create | App\Http\Controllers\[email protected] | locationRouteValidator |
| | DELETE | api/location/{location} | api.location.destroy | App\Http\Controllers\[email protected] | locationRouteValidator |
| | PATCH | api/location/{location} | | App\Http\Controllers\[email protected] | locationRouteValidator |
| | GET|HEAD | api/location/{location} | api.location.show | App\Http\Controllers\[email protected] | locationRouteValidator |
| | PUT | api/location/{location} | api.location.update | App\Http\Controllers\[email protected] | locationRouteValidator |
| | GET|HEAD | api/location/{location}/edit | api.location.edit | App\Http\Controllers\[email protected] | 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}
。
但是,如果我只使用默認的中間件代碼運行,頁面將返回白色而不顯示任何內容。我從路由中刪除中間件,並按預期顯示文本。
我知道我可以將中間件附加到控制器上,但是我想將它附加到路由中,以便我可以使用路由的組功能編寫和應用一些常見的中間件,這應該是可行的吧?
你們認爲我哪裏錯了?預先感謝您的期待!
你有沒有在kernel.php上註冊中間件? –
這是問題所在!我是新來的,所以錯過了這一步! – coderkane