Search code examples
laravellaravel-5laravel-resource

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


Solution

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