samedi 14 septembre 2019

How to return data from nested models in Laravel 5.8

I have four models for: countries > libraries > books > chapters. Each country has multiple libraries, which have multiple books consisting of multiple chapters.

With Laravel 5.8, how do I retrieve a list of all chapters of all books of all libraries of a specific country based on the slug?

Country model:

class Country extends Model
{
    public function libraries() {
        return $this->hasMany(Library::class);
    }
}

Library model:

class Library extends Model
{
    public function country() {
        return $this->belongsTo(Country::class);//country_id
    }

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

Book model:

class Book extends Model
{    
    public function library() {
        return $this->belongsTo(Library::class);//library_id
    }

    public function chapters() {
        return $this->hasMany(Chapter::class);
    }
}

Chapter model:

class Chapter extends Model
{   
    public function book() {
        return $this->belongsTo(Book::class);//book_id
    }
}

I've been trying to retrieve the data as follows, without success:

CountryController:

namespace App\Http\Controllers;

use App\Country;
use App\Http\Controllers\Controller;

class CountryController extends Controller
{
    public function show($slug)
    {    
        $country = Country::where('slug', $slug)->first();
        $chapters = $country->with('libraries.books.chapters');
        dd($chapters);
    }

    public function getRouteKeyName()
    {
        return 'slug';
    }
}

Router:

Route::get('/countries/{slug}', 'CountryController@show');

I am not getting a specific, error, but the returned data does not exist. When I expand #model in the returned dump, I see exists: false, although eager loading seems to be correct.

Builder {#217 ▼
  #query: Builder {#213 ▶}
  #model: Country {#218 ▶}
  #eagerLoad: array:3 [▼
    "libraries" => Closure() {#221 ▶}
    "libraries.books" => Closure() {#224 ▶}
    "libraries.books.chapters" => Closure() {#220 ▶}
  ]
  #localMacros: []
  #onDelete: null
  #passthru: array:17 [▶]
  #scopes: []
  #removedScopes: []
}



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire