Framework: [Eloquent] API Resources : links and metas removed when load() relationship

Created on 25 Jan 2018  路  2Comments  路  Source: laravel/framework

  • Laravel Version: 5.5.32
  • PHP Version: 7.1
  • Database Driver & Version: Mysql

Description:

When I load() relationships the links and metas disappear. Only the data remains.
If I remove the load('item', 'user') links and metas work but the relationship are not loaded.
Am I doing it wrong?

Steps To Reproduce:

Controller

$messages = Message::where('user_id', $this->auth->user()->id)->paginate(2);

return MessageResource::collection($messages->load('item', 'user'));

Class MessageResource extends Resource

    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'from_id' => $this->from_id,
            'to_id' => $this->to_id,
            'content' => $this->content,
            'item_id' => $this->item_id,
            'created_at' => $this->present()->created_at,
            'readed_at' => $this->readed_at,
            'deleted_at' => $this->deleted_at,
            'item' => new ItemResource($this->whenLoaded('item')),
            'user' => new UserResource($this->whenLoaded('user'))
        ];
    }

Most helpful comment

$this->load() returns an eloquent collection.

Try changing it to this..

$messages = Message::with('item', 'user')->where('user_id', $this->auth->user()->id)->paginate(2);
return MessageResource::collection($messages);

All 2 comments

$this->load() returns an eloquent collection.

Try changing it to this..

$messages = Message::with('item', 'user')->where('user_id', $this->auth->user()->id)->paginate(2);
return MessageResource::collection($messages);

Correct thx

Was this page helpful?
0 / 5 - 0 ratings