亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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 關注
  • 185 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號