Laravel 基本 Route 有6種:

Route::get($url, $callback);
Route::post($url, $callback);
Route::put($url, $callback);
Route::patch($url, $callback);
Route::delete($url, $callback);
Route::options($url, $callback);

下面兩種是比較特殊的用法

// 當網址輸入 $url , 無論是 get 還是 post 都會打到這個 Route
Route::match(['get', 'post'], $url, $callback);

// 當網址輸入 $url , 無論是用哪種方法都會打到這個 Route
Route::any($url, $callback);

路由傳遞參數

 // 當然變數不一定要取 $id, 就算取 $i 也可以, laravel 只是把網址 {id} 的值傳進去 function 而已!
Route::get('/user/{id}', function($id) {  
    echo 'user ' . $id;
});

// 使用 - 也可以傳遞參數, 但是建議不要使用!
Route::get('/user-{id}', function($userid) {    
    echo 'userid: ' . $userid;
});

// 使用 _ 也可以傳遞參數, 使用 _ 比使用 - 來的好!
Route::get('/user_{id}', function($userid) {    
    echo 'userid: ' . $userid;
});

// 可利用 Route 傳遞多個變數
Route::get('posts/{post}/comments/{comment}', function($postId, $commentId) { 
    echo 'postID: ' . $postId . ', ' . 'commentId: ' . $commentId;
});

可選參數

 // 意思就是, 路徑可以打 /user 不需要id , 但是 function 參數就必須給預設值, 也能給null 
Route::get('/user/{id?}', function($userid = 0) {
    echo 'userid: ' . $userid;
});


// 若不給 comment 參數可以正常執行!
Route::get('posts/{post}/comments/{comment?}', function($postId, $commentId = 0) {    
    echo 'postID: ' . $postId . ', ' . 'commentId: ' . $commentId;
});

// 但是不給 post 參數就會出現錯誤訊息, 因為系統會無法將 /posts/comments 路徑與下方 Route 做搭配
Route::get('posts/{post?}/comments/{comment?}', function($postId = 0, $commentId = 0) {    
    echo 'postID: ' . $postId . ', ' . 'commentId: ' . $commentId;
});

// 結論是, 若有多個參數, 只有最後一個參數可作為可選參數!

參數約束(可以限制參數的型態, 可以防止攻擊與 SQL 的注入)

 // 限制 id 參數只能輸入數字, 若輸入字串就會出錯
Route::get('/user/{id}', function($id) {
    echo 'userid: ' . $id;
})->where( 'id', '[0-9]+' );

如我不想要每次 Route 都打一次規則, 也可以在 RouteServiceProvider 裡的 boot function 裡面使用 pattern 方法。

 // 如此一來, 所有的 id 都會套用此規則, 不用特地在 Route 的地方打上 where 條件!
public function boot(Router $router)
{
    $router->pattern('id', '[0-9]+');
    parent::boot($router);
}
arrow
arrow
    文章標籤
    route laravel Http
    全站熱搜

    Mayuge 發表在 痞客邦 留言(0) 人氣()