laravel中路由的詳解和例項總結
路由其實就是從源地址傳送到目的地,下面對mvc+route進行圖形詳解
基礎路由:
Route::get('/get',function(){
return 'get';
});
Route::post('/post',function(){
returnho 'post';
});
Route::put('/put',function(){
return 'put';
});
Route::delete('/delete',function(){
returno 'delete';
});
Route::patch('/patch',function(){
returno 'patch';
});
Route::options('/delete',function(){
return 'delete';
});
// 匹配[]裡面的路由資訊
Route::match(['get', 'post','put'], '/getPost', function () {
return 'Hello World';
});
//匹配任何一個
Route::any('foo', function () {
return 'Hello World1';
});
必選引數路由:引數是必填項,
Route::get('/updateinfo/{id}',function($id){
echo '這是使用者後臺'.$id;
});
Route::get('posts/{post}/comments/{comment}', function ($postId, $commentId) {
echo '這是使用者後臺'.$postId. ':'.$commentId;
});
可選引數路由
Route::get('user/{name?}', function ($name = null) {
return $name;
});
Route::get('user/{name?}', function ($name = 'John') {
return $name;
});
例如:
Route::get('posts/{post}/comments/{comment?}', function ($postId, $commentId =null) {
echo '這是使用者後臺'.$postId. ':'.$commentId;
});
路由引數進行型別限制(採用正則方式)
Route::get('user/{name}', function ($name) {
//後面跟where進行正則的校驗
})
->where('name', '[A-Za-z]+');
設定全域性路由限制
/**
* 定義你的路由模型繫結,模式過濾器等。
*
* @param \Illuminate\Routing\Router $router
* @return void
*/public function boot(Router $router){
$router->pattern('id', '[0-9]+');
parent::boot($router);}
在此呼叫路由時,就不需要在填寫where設定
注意:在多個引數時,一般最後一個引數可以選擇可選的,如果第一個引數或者中的某些引數設定為可選引數則報錯誤資訊
使用路由:
路由請求方式主要分為:post、get、put、delete、patch、options等。
在使用put時序Route::put('/edit',function(){}時,需在表單新增隱藏域來確認這是一條
put資料,否則會提示錯誤,同理在delete也是
<input type="hidden" name="_method" value="PUT" size="50" /><br>
<input type="hidden" name="_method" value="DELETE" size="50" /><br>
路由錯誤提示:
1、路由錯誤提示:MethodNotAllowedHttpExceptioninRouteCollection.php line 219:
意思:當前的請求方式和路由的規則請求方式不匹配
2、InvalidArgumentExceptioninFileViewFinder.php line 137:View [from] not found.
意思:沒有發現from檢視模板檔案,注意:在laravel中模板檔案存在resources/中,
以from.blade.php中 blade必須存在遵循laravel框架命名規則
3、TokenMismatchException in VerfyCsrfToken.phpline 53.
意思:當前post請求中缺少驗證資訊注意:需要在from表單中新增token隱藏域 {{csrf_field()}}防止csrf攻擊
***剛才也說了,路由只是一個橋樑,如何使用路由把檢視層和控制層連線起來呢?
答:官網手冊裡設這樣寫的View層程式碼:
<form method="POST" action="/password/email">
{!! csrf_field() !!}
@if (count($errors) > 0)
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
@endif
<div>
Email <input type="email" name="email" value="{{ old('email') }}">
</div>
<div>
<button type="submit">
傳送重置密碼郵件 </button>
</div></form>
路由程式碼:
Route::post('password/email', 'Auth\[email protected]');
Auth:進行許可權驗證操作通過後傳到
PasswordController控制器中
在laravel中mvc+路由之間的關係圖解: