Laravel / Laravel Models and Eloquent ORM

Using Migrations and Seeders Effectively

A tutorial about Using Migrations and Seeders Effectively

Tutorial 2 of 5 5 resources in this section

Section overview

5 resources

Explores 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

  1. To create a migration, use the make:migration Artisan command:
    php artisan make:migration create_users_table
    Laravel will automatically create a new migration file in the "database/migrations" directory.

  2. Open the migration file and you will see two methods, up() and down().

  3. The up() method is used to add new tables, columns, or indexes to your database.
  4. The down() method should reverse the operations performed by the up() method.

  5. Run the migration with the migrate Artisan command:
    php artisan migrate

Using Seeders

  1. To generate a seeder, use the make:seeder Artisan command:
    php artisan make:seeder UsersTableSeeder
    This will place a new seeder file in your "database/seeds" directory.

  2. In the run method of your seeder file, you may use the DB facade to manually insert data into your database.

  3. To execute your seeder, use the db:seed Artisan 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

  1. Exercise 1: Create a migration for a 'products' table with columns: 'id', 'name', 'description', 'price', and 'created_at' and 'updated_at' timestamps.

  2. Exercise 2: Create a seeder for the 'products' table that inserts five different products.

  3. 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.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Robots.txt Generator

Create robots.txt for better SEO management.

Use tool

Case Converter

Convert text to uppercase, lowercase, sentence case, or title case.

Use tool

AES Encryption/Decryption

Encrypt and decrypt text using AES encryption.

Use tool

Countdown Timer Generator

Create customizable countdown timers for websites.

Use tool

Keyword Density Checker

Analyze keyword density for SEO optimization.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI 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 article

AI 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 article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help