How to get laravel nested relationship with eager loading

How to get multiple nested relationship data in one query. Laravel nested eager loading example. Nested eager loading laravel example. Best way to load nested relationship data in laravel 7, laravel 8 and laravel 9.

Laravel nested eager loading

When you get relationship data by with() method in single query called eager loading. Eager loading is optimizing your query. Nested relationships are multi-level relationships with one model related to the second and the second model related to the third then nested eager loading gets all data in optimized way.

Example of nested eager loading

Now we take an example of three-level nested eager loading there are four tables shops, products, orders and order_details and our relationship define as a shop has multiple products, a product multiple orders and order extra detail in orderDetail. In our example we get a shop all products data with orders

ShopController
<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Shop;

class ShopController extends Controller{
  public function show(){
    $shop = Shop::with("products.orders.orderDetail")->first();
    return $shop;
  }
}
Shop model
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Shop extends Model
{
  use HasFactory;
  protected $guarded = [];

  public function products(){
    return $this->hasMany(Product::class, 'shop_id');
  }
}
Product model
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
  use HasFactory;
  protected $guarded = [];

  public function orders(){
    return $this->hasMany(Order::class, 'product_id');
  }
}
Order model
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Order extends Model
{
  use HasFactory;
  protected $guarded = [];

  public function orderDetail(){
    return $this->hasOne(OrderDetail::class, 'order_id');
  }
}
OrderDetail model
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class OrderDetail extends Model
{
  use HasFactory;
  protected $guarded = [];
}
php laravel developer anmol sharma

Anmol Sharma

I am a software engineer and have experience in web development technologies like php, Laravel, Codeigniter, javascript, jquery, bootstrap and I like to share my deep knowledge by these blogs.

Random tutorial links