Laravel 具有 1 个必需参数和可选无限参数的路由

Laravel Route with 1 required and Optional unlimited parameters

我定义了一个调用 TestController 中的测试函数的路由。

Route::get('/test/{function_name}','TestController@test');

此测试函数在内部调用与 TestController 中的名称相匹配的函数。

这适用于不需要参数的函数。但是某些功能需要参数,然后路由无效。

public function test($function_name)
{
    try
    {
        var_dump($this->$function_name());
        return;
    }
    catch(Exception $ex)
    {
        throw $ex;
    }
}

// This functions get called fine
public function getRecord(){}

// But this functions does not work because i am passing extra paramters in the url which in turns makes the route invalid

public function getRecordByNameAndPrice($name, $price){}

那么有什么方法可以让我定义一个路由,使其包含 1 个参数但还应该允许 N 个额外参数,以便我可以调用那些需要参数的函数。

谢谢

使用 where 方法允许您的其余部分包含斜线:

Route::get('test/{func}/{rest?}', 'TestController@test')->where('rest', '.*');

然后使用$request->segments()将它们全部作为单独的值:

public function test($method, Request $request)
{
    $params = array_slice($request->segments(), 2);

    return call_user_func_array([$this, $method], $params);
}

别忘了use Illuminate\Http\Request置顶。

假设你的url是
/products?id=999&format=json&apikey=123456
并像这样定义你的路线

Route::get('/prodcuts',function(){
    return Request::all();
})
//  output

{"id":"999","format":"json","apikey"=>"123456"}