Laravel 4:路线返回错误的信息

时间:2014-05-20 22:59:11

标签: laravel laravel-4 laravel-routing

我正在使用Laravel设置API,以便我可以连接AngularJS前端。

我有2条路由转到相同的控制器方法 - > BallController@getSpecs

我的路线设置如下:

Route::group(['prefix' => '/api/v1', 'before' => 'auth.basic'], function() {
    Route::group(['prefix' => '/ball'], function() {
        Route::get('/', 'BallController@getIndex');
        Route::get('{id}', 'BallController@getIndex');
        Route::get('specs', 'BallController@getSpecs');
        Route::get('{id}/specs', 'BallController@getSpecs');
    });
});

现在我遇到Route::get('specs', 'BallController@getSpecs');路线问题。

getSpecs方法定义如下:

public function getSpecs($id = null) 
{
    if(empty($id))
    {
        Ball::all()->each(function($ball) {
            $json = [$ball->id => [
                'name'          => $ball->name,
                'core'          => $ball->core->toArray(),
                'coverstock'    => $ball->coverstock->toArray(),
                'finish'        => $ball->finish->toArray(),
                'manufacturer'  => $ball->manufacturer->toArray()
            ]];
        });

        return Response::json($json);
    }
    else
    { 
        $ball = Ball::find($id);

        if(empty($ball))
        {
            return Response::json('You\'ve got no ballss', 404);
        }
        else
        {
            return Response::json([$ball->id => [
                'name'          => $ball->name,
                'core'          => $ball->core->toArray(),
                'coverstock'    => $ball->coverstock->toArray(),
                'finish'        => $ball->finish->toArray(),
                'manufacturer'  => $ball->manufacturer->toArray()
            ]]);
        }
    }
}

当我调用/api/v1/ball/1/specs指定一个id时,我会收到正确的信息,但是当我调用/api/v1/ball/specs时,我的函数会返回我的错误消息'你没有球'

在此演员表中ID应为null,将我放入if语句的第一部分但由于某种原因我进入了我的其他并收到我的错误,因为显然没有提供ID并且球不存在。

任何帮助/见解将不胜感激。

编辑:我认为它可能会将其发送到错误的方法。我认为/api/v1/ball/specs已发送到BallController@getIndex而不是BallController@getSpecs

1 个答案:

答案 0 :(得分:0)

问题在于路由的这一部分:

Route::get('{id}', 'BallController@getIndex');
Route::get('specs', 'BallController@getSpecs');

当它看到" / api / v1 / ball / specs"时,它实际上会使用" id"来调用getIndex()。参数设置为" specs",因为它是第一个匹配的路径。解决这个问题的一种方法是定义"规格"在定义" {id}"之前首先路由路线。但更好的解决方案是限制" {id}"像这样的参数......

Route::get('{id}', 'BallController@getIndex')->where('id', '[0-9]+');

另一个建议是,不应该是领导" /"在你的前缀值(显然代码可能正在工作,但他们真的不应该在那里。所以完整更新的路线可能看起来像这样......

Route::group(['prefix' => 'api/v1', 'before' => 'auth.basic'], function() {
    Route::group(['prefix' => 'ball'], function() {
        Route::get('/', 'BallController@getIndex');
        Route::get('specs', 'BallController@getSpecs');
        Route::get('{id}', 'BallController@getIndex')->where('id', '[0-9]+');
        Route::get('{id}/specs', 'BallController@getSpecs')->where('id', '[0-9]+');
    });
});
相关问题