在Laravel中设置嵌套资源路由

时间:2014-10-14 17:44:29

标签: php rest laravel routing controllers

我正在我的应用程序中设置嵌套资源路由。目前,我有

// in app/routes
Route::resource("users.folders", "FolderController");

// in app/controllers/api/v2
class FolderController extends \BaseController {

    public function index($userId)
    {
        return Response::json( Sentry::getUser()->clients()->find($userId)->folders()->with("resources")->get() );
    }

    public function show($userId, $id)
    {
        if( $f = Sentry::getUser()->clients()->find($userId)->folders()->with("resources")->find($id) )
        {
            return Response::json( $f );
        }

        return Response::json(["status" => "Not Found"], 404);
    }

    // ...
}

我总是以同样的方式加载用户,但总是写Sentry::getUser()->clients()->find($userId)似乎是多余的。有没有办法在__construct函数中加载正确的用户?

我很想做像

这样的事情
class FolderController extends \BaseController {

    public function __construct( $userId )
    {
        $this->user = Sentry::getUser()->clients()->find($userId);
    }

    public function index()
    {
        return Response::json( $this->user->folders()->with("resources")->get() );
    }

    public function show($id)
    {
        if( $f = $this->user->folders()->with("resources")->find($id) )
        {
            return Response::json( $f );
        }

        return Response::json(["status" => "Not Found"], 404);
    }

    // ...
}

但这会导致异常。

1 个答案:

答案 0 :(得分:0)

我认为这不可能,但您可以将此代码移至功能:

private function getUsers($id) {
   return Sentry::getUser()->clients()->find($userId);
}

现在可以使用的功能:

return Response::json( $this->getUsers($userId)->folders()->with("resources")->get() );