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

Yahya Uddin
  • 26,997
  • 35
  • 140
  • 231
Khirad Zahra
  • 843
  • 2
  • 17
  • 42

3 Answers3

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),
    ];
}
Yahya Uddin
  • 26,997
  • 35
  • 140
  • 231
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),
                ];
        }
}
Kuro
  • 11
  • 1
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())
                ];
        }
}
Haritsinh Gohil
  • 5,818
  • 48
  • 50