Laravel 11 - N+1 Problem - Lazy vs Eager Loading
Laravel 11 - N+1 Problem - Lazy vs Eager Loading
In this tutorial, we will discuss the N+1 problem in Laravel 11 and explore its implications for query performance and application efficiency.
If you're a video person, feel free to skip the post and check out the video instead!
We will explore the N+1 problem in Laravel 11 through practical examples. We'll walk through the process of creating a Post model, defining relationships, and observing how lazy loading can lead to excessive queries. Then, we'll see how eager loading can optimize our queries effectively. Let’s dive in!
Step # 1 : Create Post Model, Migration & Factory.
Command : php artisan make:model Post -mf
Step # 2 : Update Post Migration.
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained()->onDelete('cascade'); // Foreign key for user
$table->string('title');
$table->text('content');
$table->timestamps();
});
}
Step # 3 : Run the Migration.
Command : php artisan migrate
Step # 4 : Define Relationships.
public function posts() // A user can have many posts
{
return $this->hasMany(Post::class);
}
public function user() // Each post belongs to a user
{
return $this->belongsTo(User::class);
}
Step # 5 : Update PostFactory.php.
<?php
namespace Database\Factories;
use App\Models\Post;
use Illuminate\Database\Eloquent\Factories\Factory;
class PostFactory extends Factory
{
protected $model = Post::class;
public function definition()
{
return [
'title' => $this->faker->sentence,
'content' => $this->faker->paragraph,
];
}
}
Step # 6 : Update DatabaseSeeder.php.
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use App\Models\User;
use App\Models\Post;
class DatabaseSeeder extends Seeder
{
public function run(): void
{
// Create 10 users and for each user, create 3 posts
User::factory(10)->create()->each(function ($user) {
Post::factory(5)->create(['user_id' => $user->id]); // Associate posts with user
});
}
}
Step # 7 : Run the Seeder.
Command : php artisan db:seed
Step # 8 : Let's See N+1 Problem in action.
Command : php artisan serve.
127.0.0.1:8000
Route::get('/', function () {
$users = User::all(); // 1 query to fetch all users
foreach ($users as $user) {
echo $user->posts; // N queries to fetch posts for each user on demand (N = number of users)
}
return view('welcome');
});
Route::get('/', function () {
$users = User::with('posts')->get(); // **1 query to fetch all users and their posts**
foreach ($users as $user) {
echo $user->posts; // No additional queries are made for posts
}
return view('welcome');
});
Share this with friends!
To engage in commentary, kindly proceed by logging in or registering
Subscribe to Our Newsletter
Stay ahead of the curve! Join our newsletter to see what everyone’s talking about.
0 Comments