阅读(4397) (0)

Laravel 8 默认值

2021-06-25 09:32:00 更新

对于某些应用程序,你可能希望为某些 URL 参数的请求范围指定默认值。例如,假设有些路由定义了 {locale} 参数:

Route::get('/{locale}/posts', function () {
    //
})->name('post.index');

每次都通过 locale 来调用辅助函数 route 也是一件很麻烦的事情。 因此,使用 URL::defaults 方法定义这个参数的默认值,可以让该参数始终存在当前请求中。然后就能从 路由中间件 调用此方法来访问当前请求:

<?php

namespace App\Http\Middleware;

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

class SetDefaultLocaleForUrls
{
    public function handle($request, Closure $next)
    {
        URL::defaults(['locale' => $request->user()->locale]);

        return $next($request);
    }
}

一旦设置了 locale 参数的默认值,您就不再需要通过辅助函数 route 生成 URL 时传递它的值。