重寫原因
近期在使用Laravel開發專案過程中,為了簡化路由程式碼使用了Laravel的資源路由,Route::resource(`photo`, `PhotoController`);
在預設情況下,Laravel生成的路由表如下:
動作 | 路徑 | Action | 路由名稱 |
---|---|---|---|
GET | /photo | index | photo.index |
GET | /photo/create | create | photo.create |
POST | /photo | store | photo.store |
GET | /photo/{photo} | show | photo.show |
GET | /photo/{photo}/edit |
edit | photo.edit |
PUT/PATCH | /photo/{photo} | update | photo.update |
DELETE | /photo/{photo} | destroy | photo.destroy |
為了滿足專案需求,需將/photo/{photo}/edit
路徑改為 /photo/edit/{photo}
實現步驟
查詢了Laravel原始碼,發現此路徑生成的方法在IlluminateRoutingResourceRegistrar.php
類中,我們需重寫此類的addResourceEdit方法即可。
-
重寫addResourceEdit方法
建立新類AppRoutingResourceRegistrar.php
,程式碼如下:
namespace AppRouting;
use IlluminateRoutingResourceRegistrar as OriginalRegistrar;
class ResourceRegistrar extends OriginalRegistrar
{
/**
* Add the edit method for a resourceful route.
*
* @param string $name
* @param string $base
* @param string $controller
* @param array $options
* @return IlluminateRoutingRoute
*/
protected function addResourceEdit($name, $base, $controller, $options)
{
$uri = $this->getResourceUri($name).`/`.static::$verbs[`edit`].`/{`.$base.`}`;
$action = $this->getResourceAction($name, $controller, `edit`, $options);
return $this->router->get($uri, $action);
}
}
-
在AppServiceProvider中註冊這個類
public function boot()
{
//重寫資源路由
$registrar = new AppRoutingResourceRegistrar($this->app[`router`]);
$this->app->bind(`IlluminateRoutingResourceRegistrar`, function () use ($registrar) {
return $registrar;
});
}
最後使用Route::resource(`photo`, `PhotoController`);生成的路由就滿足需求了。