Multiple API Resources in one call using laravel
Asked Answered
M

3

5

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

Medor answered 22/11, 2018 at 9:58 Comment(0)
A
9

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),
    ];
}
Airlie answered 22/11, 2018 at 12:54 Comment(1)
Thank you this is what i was looking farMedor
S
1

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),
                ];
        }
}
Sphericity answered 4/2, 2020 at 13:22 Comment(0)
P
0

I am using laravel 6.x, And i don't know laravel is converting the response or doing something but i am getting the response as JSON in following condition also:

class HomeController extends Controller
{
    public function index()
        {
            return [
                'advertisements' => new AdvertisementCollection(Advertisement::latest()->get()),
                'banners' => new BannerCollection(Banner::latest()->get()),
                'sliders' => new SliderCollection(Slider::latest()->get())
                ];
        }
}
Paley answered 17/12, 2019 at 11:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.