4

In Laravel (with Fractal Transformers), I'm trying to figure out how to handle nested resources exactly. Lets say I have these routes:

Route::resource('user', 'UserController');
Route::resource('user.activity', 'UserActivityController');

So if I wanted to get all users, the uri is /user, And if I want User 5, it's /user/5

Now, if I want the Activity for a User, the uri is user/1/activity.

Here's where I get a little confused. In the UserActivityController, you might have:

public function index($user_id)
{
    $user = $this->user->find($user_id)->activity;
    return $this->respondWithItem($user, $this->transformer);
}

So here's what I'm confused about:

1) For each nested resource, do I keep fetching the top parent resource (User in this case)? Lets say user has nested resources 3 or 4 levels deep (i.e. /user/1/activity/5/mentions/6/somethng-else)? Does each Resource Controller just need to keep starting from the top and working down?

2) As I'm using Fractal, is has support for includes which allows me to load related data as needed by appending certain data to includes in the query string. In fact, it's so flexible that I feel I could use a base (like User) and get every other bit of data I need from clever include usage. So, is it preferable to just do this rather than using sub resources and sub resource controllers?

2
  • You cannot use both resources on user. This will cause conflict. Commented Feb 18, 2016 at 21:35
  • @JilsonThomas my mistake. updated. Commented Feb 18, 2016 at 21:40

1 Answer 1

4

Yes, you need to fetch the models using the id. Even though it's nested resources, it isn't sharing any data in common. So you'll have to fetch everything in each Controller.

eg:

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;

class UserActivityController extends Controller
{
    /**
     * Show the specified user activity.
     *
     * @param  int  $userId
     * @param  int  $acitivityId
     * @return Response
     */
    public function show($userId, $acitivityId)
    {
        //  get the user, and then activity
    }


    /**
     * Show all activities from a user.
     *
     * @param  int  $userId
     * @return Response
     */
    public function show($userId)
    {
        //
    }



}

Or you can extend the UserController and in the __constructor, fetch the $user model. In this way it will be available in UserActivityController

Sign up to request clarification or add additional context in comments.

2 Comments

great, thanks for the info. I'll consider the inheritance idea as well!
Why both functions called "show"? Will this code work?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.