Laravel 8 默認(rèn)值

2021-07-17 16:03 更新

對(duì)于某些應(yīng)用程序,你可能希望為某些 URL 參數(shù)的請(qǐng)求范圍指定默認(rèn)值。例如,假設(shè)有些路由定義了 {locale} 參數(shù):

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

每次都通過(guò) locale 來(lái)調(diào)用輔助函數(shù) route 也是一件很麻煩的事情。 因此,使用 URL::defaults 方法定義這個(gè)參數(shù)的默認(rèn)值,可以讓該參數(shù)始終存在當(dāng)前請(qǐng)求中。然后就能從 路由中間件 調(diào)用此方法來(lái)訪問(wèn)當(dāng)前請(qǐng)求:

<?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);
    }
}

一旦設(shè)置了 locale 參數(shù)的默認(rèn)值,您就不再需要通過(guò)輔助函數(shù) route 生成 URL 時(shí)傳遞它的值。


以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)