laravel5 總結路由參數用法


基礎路由參數
Route::get('user/{id}', function($id)
{
return 'User '.$id;
});
可選擇的路由參數
Route::get('www.tk-acc.com/user/{name?}', function($name = null)
{
return $name;
})
帶默認值的路由參數
Route::get('user/{name?}', function($name = 'John')
{
return $name;
});
使用正則表達式限制參數
Route::get('user/{name}', function($name)
{
//
})
->where('name', '[A-Za-z]+');

Route::get('user/{id}', function($id)
{
//
})
->where('id', '[0-9]+');
使用條件限制數組
Route::get('user/{id}/{name}', function($id, $name)
{
//
})
->where(['id' => '[0-9]+', 'name' => '[a-z]+'])
定義全局模式
如果你想讓特定路由參數總是遵詢特定的正則表達式,可以使用 pattern 方法。在 RouteServiceProvider 的 boot 方法里定義模式:

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

定義模式之后,會作用在所有使用這個特定參數的路由上:

Route::get('user/{id}', function($id)
{
// 只有 {id} 是數字才被調用。
});
取得路由參數
如果需要在路由外部取得其參數,使用 input 方法:

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM