В вашем сценарии вам не нужно использовать модель для сводной таблицы, вы можете сделать следующее:
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,
];
}
}