Step 01: create fresh laravel project
composer create-project laravel/laravel performance1
Step 02: Setting Up Post model, migration and factory
php artisan make:model Post -mf
Step 03: Specifying migration definition in database\migrations\2022_07_31_183018_create_posts_table.php
Schema::create('posts', function (Blueprint $table) { $table->id(); $table->foreignId('user_id')->constrained(); $table->string('title'); $table->text('post_text'); $table->timestamps(); });
Step 04: Specifying default length 200 in AppServiceProvider.php with Schema facade under boot() method to avoid mysql string length too long error while executing migration command.
Schema::defaultStringLength(200);
Step 05: Defining database name in .env file
Step 06: Specifying data definition in PostFactory.php
use App\Models\Post;
protected $model = Post::class;
public function definition() { return [ 'title' => $this->faker->text(50), 'post_text' => $this->faker->text(500), ]; }
Step 07: Creating UserSeeder.php using artisan command
php artisan make:seeder UserSeeder
Step 08: Specifying definition of UserSeeder.php
public function run() { User::factory(10) ->has(Post::factory(3)) ->create(); }
Step 09: Using run method in DatabaseSeeder.php for executing UserSeeder to run migrations for user and post table. Relation is 1. user hasMany posts 2. post belongsTo user
// DatabaseSeeder.php
$this->call([ UserSeeder::class, ]);
//In User.php public function posts() { return $this->hasMany(Post::class); } //In Post.php public function user() { return $this->belongsTo(User::class); }
Step 10: Installing laravel debugbar to check performance for eloquent queries
composer require barryvdh/laravel-debugbar
Step 11: Finally running following artisan command to run migration and seeding database tables. In Users table there will be 10 users created and in Posts table there will be 3 posts for each user. So in total there will be 30 posts.
php artisan migrate:fresh --seed
Ending Note: Disabling N+1 query can be done with following code snippet in AppServiceProvider.php under boot() method
Model::preventLazyLoading(true);
To continue read on next part click here