0
votes

I have a pivot table Book_Category which store the relationship between book table and category table.

In my Book model I have this

public function categories()
    {
        return $this->belongsToMany(Category::class);
    }

In my Category Model` I have this

public function books()
{
    return $this->belongsToMany(Book::class);
}

I don't think I need a model for Book_Category since its a pivot table.

But now I need to create an API Resource. I am trying to return a Book of a particular Category

So I do this this

public function singlepage(Request $request,$book) 
$relatedCategory = BookCatResource::collection(DB::table('book_category')
                                              ->where('category_id', $request->category_id)->get());

I am using query builder because I don't have a model

In my resource, I have this

public function toArray($request)
{
    return [
        'book_id' => new BookResource($this->book),
        'category_id' => $this->category_id
   ];    
}

But it returned error

Undefined property: stdClass::$book",

1

1 Answers

0
votes

In your scenario, you do not need to use the model for pivot table, what you can do is that

Route::get('/', function () {
    return CategoryResource::collection(Category::where('id', 1)->get());
});

CategoryResource.php

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class CategoryResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->title,
            'books' => BookResource::collection($this->books),
            'created_at' => $this->created_at,
            'updated_at' => $this->updated_at,
        ];
    }
}

BookResource.php

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class BookResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'created_at' => $this->created_at,
            'updated_at' => $this->updated_at,
        ];
    }
}