Laravel / Laravel Models and Eloquent ORM
Using Migrations and Seeders Effectively
A tutorial about Using Migrations and Seeders Effectively
Section overview
5 resourcesExplores Eloquent ORM and database interactions in Laravel.
Using Migrations and Seeders Effectively
1. Introduction
This tutorial aims to guide you in effectively using Migrations and Seeders, two powerful tools for managing your database schema and initial data seeding in a Laravel application.
By the end of this tutorial, you will be able to:
- Understand the concept of migrations and seeders
- Use migrations to create and update your database schema
- Use seeders to populate your database with initial data
Prerequisites
- Basic understanding of PHP and Laravel
- Laravel installed on your local development machine
- Basic knowledge of SQL
2. Step-by-Step Guide
Migrations are like version control for your database, allowing your team to modify and share the application's database schema easily.
Seeders, on the other hand, are used to populate your database with data for testing and initial application setup.
Using Migrations
-
To create a migration, use the
make:migrationArtisan command:
php artisan make:migration create_users_table
Laravel will automatically create a new migration file in the "database/migrations" directory. -
Open the migration file and you will see two methods,
up()anddown(). - The
up()method is used to add new tables, columns, or indexes to your database. -
The
down()method should reverse the operations performed by theup()method. -
Run the migration with the
migrateArtisan command:
php artisan migrate
Using Seeders
-
To generate a seeder, use the
make:seederArtisan command:
php artisan make:seeder UsersTableSeeder
This will place a new seeder file in your "database/seeds" directory. -
In the run method of your seeder file, you may use the
DBfacade to manually insert data into your database. -
To execute your seeder, use the
db:seedArtisan command:
php artisan db:seed
3. Code Examples
Example Migration
Below is an example of a basic migration to create a new 'users' table:
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
Example Seeder
Below is an example of a basic seeder that inserts data into the 'users' table:
use Illuminate\Database\Seeder;
class UsersTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
DB::table('users')->insert([
'name' => 'John Doe',
'email' => 'john@example.com',
]);
}
}
4. Summary
In this tutorial, we've learned how to use migrations to create and update our database schema, and seeders to populate our database with initial data.
For further learning, you should explore more complex migration operations, like adding indexes or foreign keys, and using model factories in combination with seeders to generate large amounts of test data.
5. Practice Exercises
-
Exercise 1: Create a migration for a 'products' table with columns: 'id', 'name', 'description', 'price', and 'created_at' and 'updated_at' timestamps.
-
Exercise 2: Create a seeder for the 'products' table that inserts five different products.
-
Exercise 3: Modify the 'products' table migration to add a 'category_id' column. Create a 'categories' table with 'id' and 'name' columns. Add a foreign key constraint to the 'products' table that references the 'id' on the 'categories' table.
Solutions:
Solution for Exercise 1:
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->text('description');
$table->decimal('price', 8, 2);
$table->timestamps();
});
Solution for Exercise 2:
DB::table('products')->insert([
['name' => 'Product 1', 'description' => 'This is product 1', 'price' => 9.99],
['name' => 'Product 2', 'description' => 'This is product 2', 'price' => 19.99],
// ... Add 3 more products here
]);
Solution for Exercise 3:
Schema::create('categories', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
});
Schema::table('products', function (Blueprint $table) {
$table->unsignedInteger('category_id');
$table->foreign('category_id')->references('id')->on('categories');
});
Need Help Implementing This?
We build custom systems, plugins, and scalable infrastructure.
Related topics
Keep learning with adjacent tracks.
Popular tools
Helpful utilities for quick tasks.
Latest articles
Fresh insights from the CodiWiki team.
AI in Drug Discovery: Accelerating Medical Breakthroughs
In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…
Read articleAI in Retail: Personalized Shopping and Inventory Management
In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …
Read articleAI in Public Safety: Predictive Policing and Crime Prevention
In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…
Read articleAI in Mental Health: Assisting with Therapy and Diagnostics
In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…
Read articleAI in Legal Compliance: Ensuring Regulatory Adherence
In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…
Read article