使用laravel在一次调用中使用多个API资源

使用laravel在一次调用中使用多个API资源,laravel,laravel-5,laravel-resource,Laravel,Laravel 5,Laravel Resource,我正在使用laravel的API资源为一个API调用将资源转换为数组,其工作正常,是否可以在一个调用中检索多个模型的数据?至于获取用户的JSON数据以及JSON页面?或者我需要一个单独的电话 这是我迄今为止所尝试的 //Controller public function index(Request $request) { $users = User::all(); $pages = Page::all(); return new UserCollection($user

我正在使用laravel的API资源为一个API调用将资源转换为数组,其工作正常,是否可以在一个调用中检索多个模型的数据?至于获取用户的JSON数据以及JSON页面?或者我需要一个单独的电话

这是我迄今为止所尝试的

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

任何帮助都将受到高度欢迎

您可以执行以下操作:

public function index(Request $request)
{
    $users = User::all();
    $pages = Page::all();
    return [
        'users' => new UserCollection($users),
        'pages' => new PageCollection($pages),
    ];
}

我使用的是
laravel 6.x
,我不知道laravel正在转换响应或做一些事情,但我在以下情况下得到的响应也是
JSON

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())
                ];
        }
}
拉威尔6

如果你喜欢下面的话,这应该是100%有效的,你实际上帮助我解决了我遇到的一个问题,这是对这个帮助的回报:3。 更改如下:

'advertisements' => new AdvertisementCollection(Advertisement::latest()->get()),
到 (将与梵蒂冈数据库或海峡数据库查询一起使用)


谢谢这是我一直在找的
'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),
                ];
        }
}