1、路由參數
- 必選參數
有時我們需要在路由中捕獲 URI 片段。比如,要從 URL 中捕獲用戶 ID,需要通過如下方式定義路由參數:
1 Route::get('/test_param/{id}', 'TestSomethingController@testParam');
1 class TestSomethingController extends Controller 2 { 3 // 4 public function testParam($id) 5 { 6 echo $id; 7 } 8 }
這個id可以直接通過參數的形式在controller的方法中直接使用。
注意:路由參數不能包含 -
字符,需要的話可以使用 _
替代。
- 可選參數
1 Route::get('/test_param/{id}/{name?}', 'TestSomethingController@testParam');
class TestSomethingController extends Controller { // public function testParam($id,$name='defaultName') { echo $id."==>".$name; } }
你可能想到了,不錯,可選參數只能位於路徑的末尾。不然laravel就蒙逼了,你到底要請求什么接口?