Laravel中默认有多个路由到控制器

编程入门 行业动态 更新时间:2024-10-27 10:20:37
本文介绍了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.

我已经尝试过此解决方案 stackoverflow/a/21865488/3903565 可以,但是并非直接针对控制器.为什么?

I have tried this solution stackoverflow/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中默认有多个路由到控制器

本文发布于:2023-10-26 10:54:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1529930.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   路由   控制器   Laravel

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!