路由參數(shù)

2018-02-24 15:51 更新

當(dāng)然,您可以獲取請(qǐng)求路由的 URI 區(qū)段。

基礎(chǔ)路由參數(shù)

Route::get('user/{id}', function($id)
{
    return 'User '.$id;
});

可選擇的路由參數(shù)

Route::get('user/{name?}', function($name = null)
{
    return $name;
})

帶默認(rèn)值的路由參數(shù)

Route::get('user/{name?}', function($name = 'John')
{
    return $name;
});

使用正則表達(dá)式限制參數(shù)

Route::get('user/{name}', function($name)
{
    //
})
->where('name', '[A-Za-z]+');

Route::get('user/{id}', function($id)
{
    //
})
->where('id', '[0-9]+');

使用條件限制數(shù)組

Route::get('user/{id}/{name}', function($id, $name)
{
    //
})
->where(['id' => '[0-9]+', 'name' => '[a-z]+'])

定義全局模式

如果你想讓特定路由參數(shù)總是遵詢特定的正則表達(dá)式,可以使用 pattern 方法。在 RouteServiceProvider 的 boot 方法里定義模式:

$router->pattern('id', '[0-9]+');

定義模式之后,會(huì)作用在所有使用這個(gè)特定參數(shù)的路由上:

Route::get('user/{id}', function($id)
{
    // 只有 {id} 是數(shù)字才被調(diào)用。
});

取得路由參數(shù)

如果需要在路由外部取得其參數(shù),使用 input 方法:

if ($route->input('id') == 1)
{
    //
}

你也可以使用 Illuminate\Http\Request 實(shí)體取得路由參數(shù)。當(dāng)前請(qǐng)求的實(shí)例可以通過(guò) Request facade 取得,或透過(guò)類型提示 Illuminate\Http\Request 注入依賴:

use Illuminate\Http\Request;

Route::get('user/{id}', function(Request $request, $id)
{
    if ($request->route('id'))
    {
        //
    }
});
以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

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

編程獅公眾號(hào)