I am using API Resources for laravel to transform resource to array for an API call,and its working fine,Is is possible that i can retrieve data of multiple models in one call ? As to get JSON data of users along with Pages JSON ? Or i need a separate call for this.
Here what i have tried so far
//Controller
public function index(Request $request)
{
$users = User::all();
$pages = Page::all();
return new UserCollection($users);
}
//API Resource
public function toArray($request)
{
return [
'name' => $this->name,
'username' => $this->username,
'bitcoin' => $this->bitcoin,
];
}
Any help will be highly appretiated
You can do the following:
public function index(Request $request)
{
$users = User::all();
$pages = Page::all();
return [
'users' => new UserCollection($users),
'pages' => new PageCollection($pages),
];
}
laravel 6..
This should work 100% if you do like the below, you actually helped me sort out a problem i was having and this is a return on that favour :3. changes the below:
'advertisements' => new AdvertisementCollection(Advertisement::latest()->get()),
to (Will work with a vatiable or just the strait db query)
'advertisements' => AdvertisementCollection::collection(Advertisement::latest()->get())
class HomeController extends Controller
{
public function index()
{
$ads = Advertisement::latest()->get();
$banners = Banner::latest()->get();
$sliders = Slider::latest()->get()
return [
'advertisements' => AdvertisementCollection::collection($ads),
'banners' => BannerCollection::collection($banners),
'sliders' => SliderCollection::collection($sliders),
];
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With