在laravel中,路由的作用就是將用戶的不同url請求轉發(fā)給相應的程序進行處理;路由是外界訪問laravel應用程序的通路,路由定義了Laravel的應用程序向外界提供服務的具體方式,laravel的路由定義在routes文件夾中。
本文操作環(huán)境:Windows10系統(tǒng)、Laravel6版、Dell G3電腦。
laravel路由有什么作用
路由的作用就是將用戶的不同url請求轉發(fā)給相應的程序進行處理,laravel的路由定義在routes文件夾中,默認提供了四個路由文件,其中web.php文件定義基本頁面請求。
在laravel中,路由是外界訪問Laravel應用程序的通路,或者說路由定義了Laravel的應用程序向外界提供服務的具體方式。路由會將用戶的請求按照事先規(guī)劃的方案提交給指定的控制器和方法來進行處理。
基本路由
最基本的路由請求是get與post請求,laravel通過Route對象來定義不同的請求方式。例如定義一個url為'req'的get請求,返回字符串‘get response':
Route::get('req',function (){undefined return 'get response'; });
當我以get的方式請求http://localhost/Laravel/laravel52/public/req時,返回如下:
同理,當定義post請求時,使用Route::post(url,function(){});
多請求路由
如果希望對多種請求方式采用相同的處理,可以使用match或any:
使用match來匹配對應的請求方式,例如當以get或post請求req2時,都返回match response:
Route::match(['get','post'],'req2',function (){undefined return 'match response'; });
any會匹配任意請求方式,例如以任意方式請求req3,返回any response:
Route::any('req3',function (){undefined return 'any response'; });
請求參數(shù)
必選參數(shù):當以帶參數(shù)的形式發(fā)送請求時,可以在路由中進行接收,用大括號將參數(shù)括起,用/分割,例如:
Route::get('req4/{name}/{age}', function ($name, $age) {undefined return "I'm {$name},{$age} years old."; });
以get請求時將參數(shù)傳遞,結果如下:
可選參數(shù):以上的參數(shù)是必須的,如果缺少某一個參數(shù)就會報錯,如果希望某個參數(shù)是可選的,可以為它加一個?,并設置默認值,默認參數(shù)必須為最后一個參數(shù),否則放中間沒法識別:
Route::get('req4/{name}/{age?}', function ($name, $age=0) {undefined return "I'm {$name},{$age} years old."; });
正則校驗:可以通過where對請求中的參數(shù)進行校驗
Route::get('req4/{name}/{age?}', function ($name, $age=0) {undefined return "I'm {$name},{$age} years old."; })->where(['name'=>'[A-Za-z]+','age'=>'[0-9]+']);
路由群組
有時我們的路由可能有多個層級,例如定義一級路由home,其下有二級路由article,comment等,這就需要將article與comment放到home這個群組中。通過數(shù)組鍵prefix為路由article添加前綴home:
Route::group(['prefix' => 'home'], function () {undefined Route::get('article', function () {undefined return 'home/article'; }); });
這樣通過home/article就可以訪問到該路由了。
路由命名
有時需要給路由起個名字,需要在定義路由時使用as數(shù)組鍵來指定路由名稱。例如將路由home/comment命名為comment,在生成url與重定向時就可以使用路由的名字comment:
Route::get('home/comment',['as'=>'comment',function(){undefined return route('comment'); //通過route函數(shù)生成comment對應的url }]);
輸出為http://localhost/Laravel/laravel52/public/home/comment
【