Laravel中默认有多个路由到控制器 [英] Multiple routes defaults to controller in Laravel
问题描述
我希望能够通过短链接(如articles/ID
)到达文章,但我也希望通过完整链接articles/ID/category/slug
到达那里.但是我无法执行以下操作:
I want to be able to get to an article by a short-link, like this articles/ID
, but I also want to get there with the full link articles/ID/category/slug
. But I can not get the following to work:
// Route file:
Route::pattern('id', '[0-9]+');
Route::pattern('cat', '^(?!create).*');
Route::pattern('slug', '^(?!edit).*');
Route::get('articles/{id}/{cat?}/{slug?}', ['as' => 'articles.show', 'uses' => 'ArticlesController@show']);
// Controller file:
public function show($id, $cat = null, $slug = null)
{
dd('1: ' . $cat . ' | 2:' . $slug);
}
以下链接articles/28/ullam/vel-repellendus-aut-est-est-esse-fugiat
给出结果:
string(53) "1: ullam/vel-repellendus-aut-est-est-esse-fugiat | 2:"
我不明白为什么不进行拆分,如果我在路由定义中删除了?
,它会起作用.
I don't understand why it's not split, if I remove the ?
in my route definition it works.
我已经尝试过此解决方案 https://stackoverflow.com/a/21865488/3903565 可以,但是并非直接针对控制器.为什么?
I have tried this solution https://stackoverflow.com/a/21865488/3903565 and that works, but not when directed at a controller. Why?
更新;我最终重新排列了路线文件:
Route::pattern('id', '[0-9]+');
// Articles
Route::get('articles/create', ['as' => 'articles.create', 'uses' => 'ArticlesController@create']);
Route::get('articles/edit/{id}', ['as' => 'articles.edit', 'uses' => 'ArticlesController@edit']);
Route::get('articles/{id}/{category?}/{slug?}', ['as' => 'articles.show', 'uses' => 'ArticlesController@show']);
Route::get('articles/{category?}', ['as' => 'articles.index', 'uses' => 'ArticlesController@index']);
Route::resource('articles', 'ArticlesController', ['only' => ['store', 'update', 'destroy']]);
推荐答案
问题仅在于超前模式.
您需要$
和不包含/
的类才能使其正常工作.
You need $
and class excluding /
in order to make it work.
所以它们在这里:
Route::pattern('id', '[0-9]+');
Route::pattern('cat', '^(?!create$)[^/]*');
Route::pattern('slug', '^(?!edit$)[^/]*');
Route::get('articles/{id}/{cat?}/{slug?}', function($id, $cat, $slug)
{
dd($id.': ' . $cat . ' | 2:' . $slug);
});
这篇关于Laravel中默认有多个路由到控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!