请问默认值这个 url 应该如何产生?

创建middleware SetDefaultLocaleForUrls

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\URL;

class SetDefaultLocaleForUrls
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        URL::defaults(['locale'=>$request->user()->locale]);
        return $next($request);
    }
}

注册middleware

    protected $routeMiddleware = [
        ...
        'locale'=>SetDefaultLocaleForUrls::class
    ];

注册路由

Route::get('/posts',function() {
    return route('users.show', ['user'=>1]);
})->middleware('locale');

产生url

file

并不像想象的那样是 http://la57.study/en/users/1 请问应该怎么用?谢谢。

日拱一卒
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 7

路由前缀,prefix方法。详情去看看文档https://learnku.com/docs/laravel/5.7/routing/2253

5年前 评论

@Walking 谢谢,已经看了,但是还是不知道应该加在何处啊? 这个默认值的URL难道不是敲 http://hostname/posts,自动变成http://hostname/en/posts么?

5年前 评论

@hustnzj 你都定义了URL,怎么还会自动改变呢?

5年前 评论

@Walking 抱歉,图省事,造成误会了。。我的本意是:

Route::get('/posts',function() {
    return route('users.show', ['user'=>1]);
});

这样返回 http://hostname/users/1

如何通过默认值的URL这种方式,自动给返回的URL加上{locale},比如 http://hostname/en/users/1,谢谢

5年前 评论

@hustnzj 还是这句话,prefix方法。你正则匹配一下。你路由不加上prefix,你路由前缀加其他东西会报错。

5年前 评论

这个功能是设置路径参数的默认值.
如设置URL::defaults(['locale'=>'china']);,有路由
Route::get('/posts/{locale}',function() { })->name('posts');
return route('posts');返回的路径部分会是/posts/china.

5年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!