How to get items with stacked relations through multiple models in Laravel?

Viewed 26

I made a relational database where relations are kind of stacked on top of each other and every model has it's own children models, I wish to get 1 object in this case the $menu variable that will display all sections and in each section categories and each category its own items, preferably using relations

//parent 1
class FoodSection extends Model
{
    use HasTranslations, SoftDeletes;

    public $translatable = ['title'];

    protected $fillable = ['title'];

    public function foodCategory(){
        return $this->hasMany(FoodCategory::class);
    }
}

//parent 2 child 1
class FoodCategory extends Model
{
    use SoftDeletes, HasTranslations;

    public $translatable = ['title'];

    protected $fillable = ['title'];
    
    public function foodItem(){
        return $this->hasMany(FoodItem::class);
    }
    public function foodSection(){
        return $this->belongsTo(FoodSection::class);
    }
}

//parent 3 child 2
class FoodItem extends Model
{
    use SoftDeletes, HasTranslations;

    public $translatable = ['title', 'description', 'alergens'];

    protected $fillable = ['title', 'description', 'price'];

    public function foodCategory()
    {
        return $this->belongsTo(FoodCategory::class);
    }

    public function alergen()
    {
        return $this->hasMany(Alergen::class);
    }
}

//child 3
class Alergen extends Model
{
    public $translatable;
    protected $fillable = ['title'];

    public function foodItem(){
        return $this->belongsToMany(FoodItem::class);
    }
    use HasTranslations, SoftDeletes;
}
```
And this was the attempt which I did not expect to work at all but still gave it a try since I have no idea how to query this.

````laravel
$menu = FoodSection::withTrashed()->with('foodCategory')->with('foodItem')->with('alergen')->get();
```
1 Answers

You can chain it to a with method like this

$menu = FoodSection::withTrashed()
        ->with([
            'foodCategory',
            'foodCategory.foodItem',
            'foodCategory.foodItem.alergen',
        ])
        ->get();
Related