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