Laravel REST API获取具有关系的模型

Laravel REST API获取具有关系的模型,laravel,rest,Laravel,Rest,我试图通过以下方式检索模型: _id: 1, // ====> The model (example: Message) text: 'My message', createdAt: new Date(Date.UTC(2016, 5, 11, 17, 20, 0)), user: { // ====> The model in the relationship, in this case, the USER

我试图通过以下方式检索模型:

        _id: 1, // ====> The model (example: Message)
          text: 'My message',
          createdAt: new Date(Date.UTC(2016, 5, 11, 17, 20, 0)),
          user: { // ====> The model in the relationship, in this case, the USER
            _id: 2,
            name: 'React Native',
            avatar: 'https://facebook.github.io/react/img/logo_og.png',
          },
我怎么可能用拉威尔做到这一点

我当前的代码如下所示:

public function show($id){
        $id = Group::where('id', $id)->first();
        return response()->json([
            'messages' => $id->messages,
        ]);
    }

您应该看看JSON资源:

您可以像这样编写资源:

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class Group extends JsonResource
{
    /**
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            '_id' => $this->id,
            'text' => $this->text,
            'createdAt' => $this->created_at,
            // define the User resource too
            'user' => UserResource::collection($this->users)
        ];
    }
}

但是,我如何才能用消息填充数组?我得到的是一个空数组,因为我没有将消息附加到它,但如何附加它们?:)
// use model binding here, it will retrieve your model from the ID
public function show(Group $group)
{
    return new GroupResource($group);
}