Tutorial

How To Use Migrations to Create and Manage Database Tables in Laravel

Updated on April 29, 2022
Default avatar

By Erika Heidi

Developer Advocate

How To Use Migrations to Create and Manage Database Tables in Laravel

Laravel database migrations allow developers to quickly bootstrap, destroy, and recreate an application’s database, without the need to log into the database console or run any SQL queries.

In this guide, you’ll create a database migration to set up the table where you’ll save the application links. In order to do that, you’ll use the Artisan command-line tool that comes with Laravel by default. At the end, you will be able to destroy and recreate your database tables as many times as you want, using only artisan commands.

To get started, first make sure you’re in the application’s root directory and your Docker Compose development environment is up and running:

  1. cd ~/landing-laravel
  2. docker-compose up -d
Output
landing-laravel_app_1 is up-to-date landing-laravel_nginx_1 is up-to-date landing-laravel_db_1 is up-to-date

Next, create a database migration to set up the links table. Laravel Migrations allow developers to programmatically create, update, and destroy database tables, working as a version control system for your database schema.

To create a new migration, you can run the make:migration Artisan command and that will bootstrap a new class on your Laravel application, in the database/migrations folder. This class will contain a default boilerplate code.

Remember to use docker-compose exec app to run the command on the app service container, where PHP is installed:

  1. docker-compose exec app php artisan make:migration create_links_table
Output
Created Migration: 2020_11_18_165241_create_links_table

Note: The migration name is generated based on the current date and time, and the name provided as an argument to the make:migration command. For that reason, your migration file name will differ slightly. For the exact file name, check with the following:

  1. find ~/landing-laravel/database/migrations -name '*create_links_table.php'
Output
/home/sammy/landing-laravel/database/migrations/2020_11_18_165241_create_links_table.php

Open the generated migration class using your editor of choice:

  1. nano database/migrations/2020_11_18_165241_create_links_table.php

Next, update the up method to include the table columns you’ll need to store the app data.

Replace the current content of your migration class with the following code. The highlighted values are the only lines that need adding, so if you prefer, you can also only copy those highlighted lines and include them into your Schema::create definition:

database/migrations/2020_10_12_171200_create_links_table.php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateLinksTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('links', function (Blueprint $table) {
            $table->id();
            $table->string('url', 200);
            $table->text('description');
            $table->boolean('enabled')->default(true);
            $table->timestamps();
        });
    }

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

In addition to the default fields that are included in the table definition that is automatically generated with the Artisan command, you’re including three new fields in this table:

  • url : A string field to save the link URL.
  • description : A text field to save the link description.
  • enabled : A field to store the state of the link, whether it’s enabled or not. The boolean Schema type will generate a tinyint unsigned field to store a value of either 0 of 1.

Save your migration file when you’re done adding these fields. Next, run the migration with:

  1. docker-compose exec app php artisan migrate
Output
Migration table created successfully. Migrating: 2014_10_12_000000_create_users_table Migrated: 2014_10_12_000000_create_users_table (152.46ms) Migrating: 2014_10_12_100000_create_password_resets_table Migrated: 2014_10_12_100000_create_password_resets_table (131.12ms) Migrating: 2019_08_19_000000_create_failed_jobs_table Migrated: 2019_08_19_000000_create_failed_jobs_table (101.06ms) Migrating: 2020_11_18_165241_create_links_table Migrated: 2020_11_18_165241_create_links_table (60.20ms)

You’ll notice that other migrations were also executed along with the create_links_table. That is because the default Laravel installation comes with migrations for users (with a users table and a password_resets table) and for queued jobs (with a failed_jobs table). Because your demo application won’t use these features, it is safe to remove those migrations now; however, you may also opt to leave them in place if you are working on an application of your own and you plan on developing it further. All migration files are located at database/migrations in the app’s root folder.

For more detailed information on database migrations, please refer to our guide on How To Use Database Migrations and Seeders to Abstract Database Setup in Laravel.

In the next part of this series, you’ll create a custom Artisan command to list, insert, and delete entries in the app’s links table.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


Tutorial Series: How To Build a Links Landing Page in PHP with Laravel and Docker Compose

Laravel is an open-source PHP framework that provides a set of tools and resources to build modern PHP applications. In this project-based tutorial series, you’ll build a Links Landing Page application with the Laravel framework, using a containerized PHP development environment managed by Docker Compose.

At the end, you’ll have a one-page website built with Laravel and managed via Artisan commands where you can share relevant links to an audience on social channels and presentations.

About the authors
Default avatar

Developer Advocate

Dev/Ops passionate about open source, PHP, and Linux.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
Leave a comment


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel