laravel路由使用【总结】

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就蒙逼了,你到底要请求什么接口?

原文地址:https://www.cnblogs.com/xxoome/p/5823683.html