Laravel / Laravel Artisan and CLI

Running Database Migrations and Seeders

In this tutorial, we will delve into Laravel's database migrations and seeders. You will learn how to create migrations to manage your database schema and seeders to populate your…

Tutorial 3 of 5 5 resources in this section

Section overview

5 resources

Explores Laravel's Artisan command-line interface for automation and productivity.

Introduction

The goal of this tutorial is to learn how to manage Laravel's database migrations and seeders. Laravel's migrations provide mechanisms for creating and modifying database tables, while seeders allow you to fill your database with test data.

By the end of this tutorial, you'll be able to:
- Create and run migrations to manage your database schema.
- Create and run seeders to populate your database with test data.

Prerequisites:
- Basic understanding of PHP and Laravel.
- Installed Laravel environment.

Step-by-Step Guide

Migrations are like version control for your database, allowing you to modify your database schema in a structured and easy-to-read manner. Seeders, on the other hand, are used to populate your database with data. This can be extremely useful when you want to populate your database with test data for testing purposes.

Creating Migrations

To create a migration, you can use the make:migration Artisan command. For example, to create a migration that creates a users table:

php artisan make:migration create_users_table

Running Migrations

To run your migrations, use the migrate Artisan command:

php artisan migrate

Creating Seeders

To generate a seeder, you may use the make:seeder Artisan command. For example, to create a seeder for the users table:

php artisan make:seeder UsersTableSeeder

Running Seeders

To run your seeders, use the db:seed Artisan command:

php artisan db:seed

Code Examples

Here are some practical examples:

Migrations

Here's an example of a migration to create a users table:

<?php

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->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('users');
    }
}

Seeders

Here's an example of a seeder for the users table:

<?php

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;

class UsersTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        DB::table('users')->insert([
            'name' => Str::random(10),
            'email' => Str::random(10).'@gmail.com',
            'password' => Hash::make('password'),
        ]);
    }
}

Summary

In this tutorial, you've learned how to create and run migrations and seeders in Laravel. You've also seen examples of how to use these features to manage your database schema and populate your database with test data.

Next steps could include exploring other features of Laravel, such as its routing, controller, or middleware features. Some recommended resources for continuing your learning include the official Laravel documentation, Laracasts, and the Laravel News blog.

Practice Exercises

  1. Create a migration to add a phone column to the users table.
  2. Create a seeder to populate the users table with 50 random users.
  3. Create a migration to create a posts table, and a seeder to populate it with 100 random posts. Each post should be associated with a user.

Remember, practice is key when it comes to programming. Keep at it, and you'll get the hang of Laravel's database functionality in no time!

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

Age Calculator

Calculate age from date of birth.

Use tool

Favicon Generator

Create favicons from images.

Use tool

CSS Minifier & Formatter

Clean and compress CSS files.

Use tool

Open Graph Preview Tool

Preview and test Open Graph meta tags for social media.

Use tool

Image Compressor

Reduce image file sizes while maintaining quality.

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