【问题标题】:Laravel Route with 1 required and Optional unlimited parametersLaravel Route 具有 1 个必需和可选的无限参数
【发布时间】:2015-11-17 01:50:43
【问题描述】:

我定义了一个路由,它调用 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 个额外参数,以便我可以调用那些需要参数的函数。

谢谢

【问题讨论】:

    标签: php laravel laravel-4 laravel-routing


    【解决方案1】:

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

    Route::get('/prodcuts',function(){
        return Request::all();
    })
    //  output
    
    {"id":"999","format":"json","apikey"=>"123456"}
    

    【讨论】:

    • 是的,但我说它应该允许 url 中的可选参数的部分在你的答案中丢失了
    • @RaheelKhan 你能给我看一个你想要包含的可选参数的 url 示例
    【解决方案2】:

    使用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 时,它会显示:page doesn't exists 并且当我使用参数调用函数时,它会失败并且没有错误消息
    • @RaheelKhan - Getting failed respone 是什么意思?您必须提供更多详细信息。
    • 是的,很抱歉我没有看到日志。这是错误Argument 2 passed to TestController::test() must be an instance of Illuminate\Http\Request, none given' in /var/www/html/hubwire_api/app/controllers/TestController.php:8
    • @RaheelKhan - 没有意识到你仍然停留在 Laravel 4 上。删除第二个参数,并改用外观:Request::segments()
    猜你喜欢
    • 2021-11-15
    • 2021-11-06
    • 2023-03-19
    • 1970-01-01
    • 2021-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多