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.
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.
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.
Please or to participate in this conversation.