Alias for a route with a fixed parameter value

半城伤御伤魂 提交于 2019-12-23 12:53:07

问题


I have this route:

Route::get('/MyModel/{id}', 'MyController@show');

The method show() accepts a parameter called id and I want to setup an alias for /MyModel/1 so it's accesible from /MyCustomURL.

I already tried a few combinations, like:

Route::get('/MyCustomURL', ['uses' => 'MyController@show', 'id' => 1]);

But I keep getting missing required argument error for method show().

Is there a clean way to achieve this in Laravel?


回答1:


In Laravel 5.4 (or maybe earlier) you can use defaults function in your routes file.

Here is example:

Route::get('/alias', 'MyModel@show')->defaults('id', 1);

In this case you don't need to add additional method in your controller.




回答2:


In same controller (in your case MyController ?) you should create one new method:

public function showAliased()
{
   return $this->show(1);
}

and now you can define your aliased route like so:

Route::get('/MyCustomURL', 'MyController@showAliased');



回答3:


define your route like this: you can use "as" to give your route any name that you need.

Route::get('/MyModel/{id}' , [
        'as'=>'Camilo.model.show',
        'uses' => 'MyController@show' ,
    ]) ;

now if you want to access this route, you can generate url for it, based on its name like this:

route('Camilo.model.show', ['id' =>1]) ;



回答4:


Route::get('MyModel/{id}', 'MyController@show');

not

Route::get('/MyModel/{id}', 'MyController@show');

Good Luck!



来源:https://stackoverflow.com/questions/37825238/alias-for-a-route-with-a-fixed-parameter-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!