Laravel - API Resources - Relationships

If you would like to include related resources in your response, you may add them to the array returned by your resource's toArray method. In this example, we will use the PostResource resource's collection method to add the user's blog posts to the resource response:

    use App\Http\Resources\PostResource;
     * Transform the resource into an array.
     * @param  \Illuminate\Http\Request  $request
     * @return array
    public function toArray($request)
        return [
            'id' => $this->id,
            'name' => $this->name,
            'email' => $this->email,
            'posts' => PostResource::collection($this->posts),
            'created_at' => $this->created_at,
            'updated_at' => $this->updated_at,
If you would like to include relationships only when they have already been loaded, check out the documentation on conditional relationships.