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、路由錯誤提示:MethodNotAllowedHttpExceptionin RouteCollection.php line 219:

意思:當前的請求方式和路由的規則請求方式不匹配 

2、InvalidArgumentExceptionin FileViewFinder.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\PasswordController@postEmail');

Auth:進行權限驗證操作通過後傳到

PasswordController控制器中

在laravel中mvc+路由之間的關係圖解:

laravel執行過程圖解.png


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章