laravel中必須先配置路由,才能使用。不像tp中不配置也能使用,由於tp能夠經過pathinfo進行自動解析。php
1、簡單的路由設置laravel
咱們通常在routes/web.php文件中配置網頁端路由。web
//參數一,表示uri路徑 //參數二,閉包函數,處理響應 Route::get('/test', function () { return '測試'; });
2、路由方法,處理特定http請求方式閉包
Route::get('/', function () {}); Route::post('/', function () {}); Route::delete('/', function () {});
也能夠經過Route::any()捕獲任意請求方式app
Route::any('/', function () {});
也能夠經過Route::match()處理指定的請求方式函數
Route::match(['get', 'post'], '/', function () {});
3、將路由映射到控制器方法post
Route::get('/hello', 'HelloController@index');
將/hello的處理映射到app/Http/Controllers/HelloController.php的index方法。測試
若是咱們在Controllers目錄下建立了多層目錄,能夠經過(目錄\...\控制器@方法)的方式:blog
Route::get('/hello', 'Hello\HelloController@index');
4、路由參數路由
有些時候須要路由上傳遞參數,只需在路由路徑中標識便可。
Route::get('/list/{page}', function ($page) { return "當前頁數{$page}"; });
不過上面的page參數是必傳的,若是沒傳將會報錯找不到。這時候能夠在標識後面加個?,表示可選,並給函數參數一個默認值。
Route::get('/list/{page?}', function ($page = 1) { return "當前頁數{$page}"; });
咱們也能夠爲路由參數設置正則規則,保證參數的正確性
Route::get('/search/{key?}/{page?}', function ($key = '', $page = 1) { return "搜索 {$key} 頁數 {$page}"; })->where(['key' => '[A-Za-z]+', 'page' => '[0-9]+']);
獲取路由參數
Route::get('/search/{key?}/{page?}', function (Request $req) { //獲取單個路由參數 var_dump($req::route('key')); //獲取全部路由參數 var_dump($req::route()->parameters()); });
經過Request::all()獲取普通參數,相似?a=a&b=b&c=c
Route::get('/search/{key?}/{page?}', function (Request $req, $key = '', $page = 1) { var_dump($key); var_dump($page); var_dump($req::all()); });
5、路由命名
咱們能夠給路由設置一個名字,方便在視圖中使用
Route::get('/list/{page?}', function ($page = 1) { return view('list', ['page' => $page]); })->name('list.page');
咱們在resources/views/list.blade.php視圖中,經過 route() 方法來顯示該路由地址
{{ route('list.page', ['page' => $page]) }}