Multiple API Resources in one call using laravel

6.2k Views Asked by At

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

3

There are 3 best solutions below

1
On BEST ANSWER

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),
    ];
}
0
On

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())
                ];
        }
}
0
On

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),
                ];
        }
}