爲了改變帕拉姆名稱Route::resource
,則需要自定義ResourceRegistrar
實現。
這裏是你如何能做到這一點在最短的可能的方式:
// AppServiceProvider (or anywhere you like)
public function register()
{
$this->app->bind('Illuminate\Routing\ResourceRegistrar', function ($app) {
// *php7* anonymous class for brevity,
// feel free to create ordinary `ResourceRegistrar` class instead
return new class($app['router']) extends \Illuminate\Routing\ResourceRegistrar
{
public function register($name, $controller, array $options = [])
{
if (str_contains($name, '/')) {
return parent::register($name, $controller, $options);
}
// ---------------------------------
// this is the part that we override
$base = array_get($options, 'param', $this->getResourceWildcard(last(explode('.', $name))));
// ---------------------------------
$defaults = $this->resourceDefaults;
foreach ($this->getResourceMethods($defaults, $options) as $m) {
$this->{'addResource'.ucfirst($m)}($name, $base, $controller, $options);
}
}
};
});
}
現在你的路線將是這樣的:
Route::resource('users', 'UsersController', ['param' => 'some_param'])
/users/{some_param}
// default as fallback
Route::resource('users', 'UsersController')
/users/{users}
記住,這種方式不能嵌套資源工作因此它們將是默認和自定義行爲的混合,如下所示:
Route::resource('users.posts', 'SomeController', ['param' => 'id'])
/users/{users}/posts/{id}
那麼你關心的路線或實際上是表單生成器? –
我更關心路線,我希望他們遵循相同的模式。例如'{資源}/{編號} /編輯' – olvlvl
那你去吧。請記住嵌套的資源 - 就像在答案中一樣。 –