【问题标题】:Routing & pretty URL路由和漂亮的 URL
【发布时间】:2020-02-17 08:33:22
【问题描述】:

我希望创建更漂亮的 URL,但在创建有效路由时遇到问题:

假设我有以下页面http://localhost/app/account/5/edit

这适用于 Route::get('account/{account}', 'AccountController@edit');

如果我修改 Account Model 并将 getRouteKeyName 修改为 return 'name',我可以(使用上面相同的 Route ) 访问以下链接:http://localhost/app/account/randomName/edit

问题是,我对一条稍微不同的路线感兴趣,即:http://localhost/app/account/randomName-5/edit

如果我创建一个路由 Route::get('/accounts/{ignore}-{account}/edit', 'AccountController@edit'),它会因为发送的第一个参数而失败要编辑的是字符串,而不是 Account 的实例。这可以通过将 edit(Account $ac) 修改为 edit($ignored, Account $ac); 轻松解决……但感觉就像在作弊。

有没有办法让路由忽略第一个 {block}?

【问题讨论】:

    标签: laravel eloquent


    【解决方案1】:

    根据文档,您可以customize your resolution logic 进行路由模型绑定。

    在这种情况下,您可以在 App\Providers\RouteServiceProvider 中执行类似的操作:

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        parent::boot();
    
        Route::bind('accountNameWithId', function ($value) {
            list($accountName, $accountId) = explode('-', $value);
    
            return App\Account::whereKey($accountId)
                ->where('name', $accountName)
                ->firstOrFail();
        });
    }
    

    然后你可以像这样重新定义你的路线:

    Route::get('account/{accountNameWithId}', 'AccountController@edit');
    

    【讨论】:

    • 这很棒!谢谢。顺便说一句,它是 explode() 而不是 implode() 另外,我删除了 where('name') 因为我实际上只是通过 account_id 进行搜索。
    猜你喜欢
    • 2017-02-02
    • 1970-01-01
    • 2021-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-07
    相关资源
    最近更新 更多