This comprehensive tutorial explains Laravel’s database essentials with a deep dive into migrations and seeders. You’ll learn step by step how to design database schemas, manage versions, and seed test data. This professional guide is designed for beginners and intermediate developers who want to master Laravel’s database layer for building scalable applications.
Every dynamic application needs a reliable and flexible database structure. Laravel, being one of the most developer-friendly frameworks, provides two powerful tools for managing databases: migrations and seeders.
Think of migrations as version control for your database schema and seeders as factories for populating data. With migrations, you can create, modify, and share your database structure with ease. With seeders, you can generate sample or essential data for testing and production.
Why Use Migrations and Seeders?
Migrations Benefits
Version control for your database schema
Collaboration across teams without conflicts
Automated schema creation and modification
Easy rollback if something goes wrong
Seeders Benefits
Populate testing data quickly
Pre-fill essential data like admin users or roles
Repeatable and sharable data creation
Integration with factories for bulk fake data
Setting Up Database Connection in Laravel
Before we dive into migrations and seeders, configure your database connection in the .env file.
Laravel will use these credentials to connect to your database. You can check configurations in config/database.php.
Introduction to Migrations
A migration is simply a PHP class that defines changes to your database structure. Migrations live in the database/migrations directory.
php artisan make:migration create_users_table
This will generate a new migration file with a timestamp prefix.
Understanding a Migration File
Here’s what a typical migration file looks like:
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamps();
});
}
public function down(): void
{
Schema::dropIfExists('users');
}
};
Key Parts:
up(): Defines what happens when the migration is run.
down(): Defines how to rollback the migration.
Running and Rolling Back Migrations
Run all migrations with:
php artisan migrate
Rollback the last batch of migrations:
php artisan migrate:rollback
Reset all migrations:
php artisan migrate:reset
Refresh all migrations (rollback + re-run):
php artisan migrate:refresh
Fresh migrate (drop all tables then migrate):
php artisan migrate:fresh
Common Migration Column Types
Laravel’s schema builder provides many column types.
Column Type
Usage
Example
string
VARCHAR
$table->string('name', 100);
text
LONGTEXT
$table->text('description');
integer
INT
$table->integer('age');
boolean
TRUE/FALSE
$table->boolean('is_active');
timestamps
created_at & updated_at
$table->timestamps();
Adding Foreign Keys
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->foreignId('user_id')->constrained()->onDelete('cascade');
$table->timestamps();
});
Here, user_id is a foreign key referencing users.id.
Introduction to Seeders
Seeders are classes that populate your database with test or essential data. They live inside database/seeders.
php artisan make:seeder UserSeeder
Writing a Seeder
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use App\Models\User;
class UserSeeder extends Seeder
{
public function run(): void
{
User::create([
'name' => 'Admin',
'email' => 'admin@example.com',
'password' => bcrypt('password'),
]);
}
}
To run all seeders, execute:
php artisan db:seed
Using Database Seeder
The DatabaseSeeder.php file calls other seeders:
public function run(): void
{
$this->call([
UserSeeder::class,
PostSeeder::class,
]);
}
Combining Seeders with Factories
Factories allow you to generate bulk fake data.
php artisan make:factory UserFactory --model=User
Inside the factory:
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
class UserFactory extends Factory
{
public function definition(): array
{
return [
'name' => fake()->name(),
'email' => fake()->unique()->safeEmail(),
'password' => bcrypt('password'),
];
}
}
Now use this in a seeder:
User::factory(10)->create();
Seeding Specific Environments
You may want different seeders for local and production.
if (app()->environment('local')) {
$this->call(UserSeeder::class);
}
Best Practices for Migrations and Seeders
Keep migrations small and specific.
Never edit old migrations that are already shared.
Use seeders for essential and reproducible data.
Combine factories with seeders for realistic test data.
Version control your migrations with Git for team collaboration.
Conclusion
Laravel migrations and seeders give you powerful control over your database structure and data population. Migrations ensure your schema evolves consistently across environments, while seeders provide the ability to populate databases with essential or testing data.
By mastering migrations and seeders, you gain confidence in handling databases professionally in Laravel projects. Whether you are building a small prototype or a large-scale enterprise system, these tools will save you countless hours and help you collaborate more effectively with your team.
This article is a comprehensive tutorial on using the Prohibited Validation Rules in Laravel. You will learn how to apply prohibited, prohibited_if, and prohibited_unless with clear explanations, real-life scenarios, and code examples. This guide is perfect for developers who want to master advanced validation techniques in Laravel applications.
This detailed tutorial explores request validation in Laravel controllers. You’ll learn multiple techniques—basic controller validation, using form request classes, custom rules, conditional validation, error handling, localization, and best practices. With practical examples, code snippets, and structured explanations, this article is designed for beginners to advance learner.
This guide teaches you how to deploy Laravel applications to production servers. From preparing your environment and configuring Nginx or Apache, to database migrations, caching, performance optimization, CI/CD pipelines, and security practices—this article covers everything step by step.It’s suitable for both beginners and advanced developers who want to ship stable, secure & scalable app.
This website uses cookies to enhance your browsing experience. By continuing to use this site, you consent to the use of cookies. Please review our Privacy Policy for more information on how we handle your data. Cookie Policy
These cookies are essential for the website to function properly.
These cookies help us understand how visitors interact with the website.
These cookies are used to deliver personalized advertisements.