Nested API Resource in Laravel

256 views Asked by At

In my Favorite Resource, I have this

public function toArray($request)
{
    return [
        'book_id' => $this->book,
        // 'book_id' => BookResource::collection($this->whenLoaded('book_id')),
        'user_id' => $this->user_id,
   ];    
}

But when I send a request to my endpoint

{
    "book_id": {
    "id": 2,
    "name": "fcdsadxa",
    "about": "xzxzxZ",
    "image_url": "#.png",
    "epub_url": "#.epub",
    "author_id": 1,
    "publisher": "dss",
    "year": 1990,
    "recommended": 1,
    "created_at": "2019-12-07 07:44:51",
    "updated_at": "2019-12-07 07:44:51",
    "pages": null
},

Is there a way to return the author details not just the ID like below

    "id": 1,
    "name": "Dragon and Box",
    "about": "dss",
    "content": null,
    "image": "h#.png",
    "recommended": 0,
    "created_at": "2019-12-07T07:44:51.000000Z",
    "updated_at": "2019-12-07T07:44:51.000000Z",
    "author": {
        "id": 1,
        "name": "Odutola Abisoye",
        "about": "dsfcds",
        "image_url": "#.png",
        "created_at": "2019-12-07 07:44:06",
        "updated_at": "2019-12-07 07:44:06"
    },

As favorite table is a pivot table between User and Book

In my Book Table, I have this

Schema::create('books', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->string('name');
    $table->text('about');
    $table->string('image_url');
    $table->string('epub_url');
    $table->integer('author_id'); 
    $table->string('publisher');  
    $table->year('year');
    $table->boolean('recommended')->default(0);
    $table->timestamps();    
});

I have done this to set up the relationship

Favorite Model

public function book ()
{
    return $this->belongsTo(Book::class);
}

public function user()
{
    return $this->belongsTo(User::class);
}

Book Model

public function favorites()
{
    return $this->hasMany(Favorite::class);
}

User Model

public function favorites()
{
    return $this->hasMany(Favorite::class);
}

This is what my favorite schema looks like

Schema::create('favorites', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->integer('book_id')->unsigned();
    $table->integer('user_id')->unsigned();
    $table->timestamps();
});
1

There are 1 answers

0
xtremeCODE On BEST ANSWER

I fixed it by returning my FavoriteResource like this

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