oleynikd's avatar

Mix in relationship to Model::get()

I have a App\Channel model. Channels have Categories:

public function categories()
{
    return $this->belongsToMany('App\Category')->withTimestamps();
}

In my ApiController I'd like to return array of channels with categories included, like:

[
    {
        "name": "Some Channel",
        "slug": "some-channel",
        "categories": ['cat 1', 'cat2', ...]
    },
    ...
]

Here's the controller method:

public function all(Request $request)
{
    return Channel::get(['name', 'slug']);
}

Of course this gives me only name and slug:

[
    {
        "name": "Some Channel",
        "slug": "some-channel"
    },
    ...
]

How can I add categories to each channel response? Thanks.

0 likes
5 replies
pmall's avatar
pmall
Best Answer
Level 56

You have to eager load the categories :

Channel::with('categories')->get();

Then if you want to format the json output I suggest you to use the fractal package.

bobbybouwmann's avatar

You can return whatever you want in a json response

public function all(Request $request)
{
    // Laravel will convert it to json by default.
    return Channel::with('categories')->get(['name', 'slug']);
}

Now you will get a different array as you showed before, but you will hav eall the data

oleynikd's avatar

@bobbybouwmann When I do like this - I get empty categories array... I Guess because of this: get(['name', 'slug'])

bobbybouwmann's avatar

Yea, you need to select the foreign key to the category as well

return Channel::with('categories')->get();
// Or
return Channel::with('categories')->get(['name', 'slug', 'category_id']);

Please or to participate in this conversation.