Jeremy
Jeremy

Reputation: 1952

Laravel Resource - Get data from relation

I'm trying to use Laravel's resources & Collection to build a small API.

I would like to recover all the posts of the categories

My relation on my model :

/*
|--------------------------------------------------------------------------
| RELATIONS
|--------------------------------------------------------------------------
*/
public function posts()
{
    return $this->belongsToMany(Post::class, 'post_category');
}

Category controller :

public function index()
{
    $categories = Category::all();

    return (new CategoryCollection(CategoryResource::collection($categories)));
}

My categoryResource :

public function toArray($request)
{
    return [
        'id'   => $this->id,
        'name' => $this->name,
        'slug' => $this->slug
    ];
}

My CategoryCollection

public function toArray($request)
{
    return [
        'data' => $this->collection,
        'posts' => PostResource::collection($this->whenLoaded('posts')),
    ];
}

I try to recover the posts of a category first. When I make the following command I get an error: Method ... relationLoaded does not exist

'posts' => PostResource::collection($this->whenLoaded('posts'))

What did I not understand?

I also created two PostCollection and PostResource files (basic, I did not modify them)

public function toArray($request)
{
    return parent::toArray($request);
}

Upvotes: 0

Views: 2573

Answers (2)

Đỗ Nhật Quang
Đỗ Nhật Quang

Reputation: 842

cannot use Resource in Collection. Use this

public function index()
{
    $categories = Category::all();

    return (new CategoryCollection($categories));
}

Upvotes: 0

amr degheidy
amr degheidy

Reputation: 317

public function index()

{
    $categories = Category::all();

    return (CategoryResource::collection($categories));
}

this is might help , try this

and if you want to use posts resource you need make posts resources and inside the CategoryResource

'posts'=>PostResource::collection($this->posts)

Upvotes: 1

Related Questions