Laravel 中的自定义路由

所以我有如下所示的路由方案。当 URI 看起来像“ audi-a4-modification-category”时 - 它工作正常。但是当我有像“ alfa-romeo-giulietta-modification-category”这样的 uri 时,因为Laravel 认为 alfa - 品牌,romeo - 模型......而且我从控制器那里得到了错误的方法。如何在不更改 URI 中的分隔符的情况下解决该问题?


Route::get('{brand}-{model}-{modification}-{category}', 'Frontend\PagesController@category')->middleware('custom-routing')->name('frontend.category');

Route::get('{brand}-{model}-{modification}', 'Frontend\PagesController@modification')->middleware('custom-routing')->name('frontend.modification');

Route::get('{brand}-{model}', 'Frontend\PagesController@model')->middleware('custom-routing')->name('frontend.model');

Route::get('{brand}', 'Frontend\PagesController@brand')->middleware('custom-routing')->name('frontend.brand');


慕的地8271018
浏览 167回答 2
2回答

catspeake

您可以在模型中定义一个增变器,例如protected $appends = ['slug'];和public function getSlugAttribute() {    $slug = $this->brand . '-' . $model . '-' . $modification . '-' . $category;    return $slug;}现在,它只是一个模型属性,您可以使用路由模型绑定概念public function getRouteKeyName(){    return 'slug';}所有在你雄辩的模型和控制器中public function show(YourModel $slug) {    return $slug;//your model instance}未经测试,但它应该可以正常工作。

MMTTMM

Laravel 文档说明如下:路由参数始终包含在 {} 大括号内,并且应该由字母字符组成,并且不能包含 - 字符。不要使用 - 字符,而是使用下划线 (_)。更多信息:https : //laravel.com/docs/5.8/routing#required-parameters一种解决方法是在生成 url 之前替换 url 部分:路线:Route::get('{brand}-{model}-{modification}-{category}', 'Frontend\PagesController@category')->middleware('custom-routing')->name('frontend.category');链接:<a href="{{ route('frontend.category', [str_replace('-', '_', 'alfa-romeo'), 'giulietta', 'modification', 'category']) }}">test</a>控制器:class PagesController{&nbsp; &nbsp; public function category(...$args)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; // or use list(...)&nbsp; &nbsp; &nbsp; &nbsp; [$brand, $model, $modification, $category] = array_map(function($urlPart) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return str_replace('_', '-', $urlPart);&nbsp; &nbsp; &nbsp; &nbsp; }, $args);&nbsp; &nbsp; &nbsp; &nbsp; return 'test';&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP