为了账号安全,请及时绑定邮箱和手机立即绑定

Laravel 中的自定义路由

Laravel 中的自定义路由

PHP
慕的地8271018 2021-12-03 15:52:25
所以我有如下所示的路由方案。当 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');
查看完整描述

2 回答

?
catspeake

TA贡献1111条经验 获得超0个赞

您可以在模型中定义一个增变器,例如


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

}

未经测试,但它应该可以正常工作。


查看完整回答
反对 回复 2021-12-03
?
MMTTMM

TA贡献1869条经验 获得超4个赞

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

{

    public function category(...$args)

    {

        // or use list(...)

        [$brand, $model, $modification, $category] = array_map(function($urlPart) {

            return str_replace('_', '-', $urlPart);

        }, $args);


        return 'test';

    }

}


查看完整回答
反对 回复 2021-12-03
  • 2 回答
  • 0 关注
  • 166 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信