Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple API Resources in one call using laravel

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

like image 964
Khirad Zahra Avatar asked Mar 06 '23 00:03

Khirad Zahra


2 Answers

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),
    ];
}
like image 79
Yahya Uddin Avatar answered Mar 15 '23 12:03

Yahya Uddin


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),
                ];
        }
}
like image 26
Kuro Avatar answered Mar 15 '23 11:03

Kuro