How to create database migration in Laravel

Laravel migrations allow you to change your database via PHP code. Having a database as code allows you to do version control your database with ease. This guide will show you how to create a Laravel database migration.

Why use Laravel Migrations?

A Laravel database migration:

  • It eliminates the need for users to go back and forth between app and database to configure and test their apps.
  • It allows for rapid deployment of Laravel apps. As a result, the user only needs to run one command to deploy their apps onto production.
This guide assumes that you already have a basic Laravel project and database setup.

Laravel Migrations: An Introduction

A Migration is a file containing a migration class representing a change in the database. And, these changes often include actions allowing you to create, delete, or update a table or a column in a table. Additionally, you can track a Laravel Migration by the time of creation. Consequently, you must avoid making direct changes to the database schema if you use migrations.

Make your first migration

First, navigate to the root directory of your Laravel project.

You can then run the following command:

php artisan make:migration <migration_name>

You can replace migration_name with the name of your migration. Furthermore, your migrations are stored in the folder: /database/migrations/.

Laravel will use this naming convention year_month_day_time_create_products_table to store your migration. So a table called: create_products_table, will for example be stored as: 2021_07_15_151222_create_products_table.

This naming convention is important because it keeps track of the migrations. Additionally, it is also useful when the user needs to roll back the changes.

The contents of this file will be something like this:

<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateProductsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->timestamps();
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('products');
    }
}

To run migrations, use the following command:

php artisan migrate

To undo the last migration, run the following command:

php artisan migrate:rollback

Understanding the migration class:

The migration class contains two methods: up() and down(). You use these methods to either make or roll back changes in the database.

The Artisan migrate command will call the up() method. Conversely, the Artisan rollback command will all the down() method. Therefore, when setting up a migration, it is wise to write code for both up and down.

The migrations use Laravel facade Schema to interact with the database.

The create method is used to create a new table, and the first argument is the table's name. The second argument is a function that accepts the table blueprint as an argument. This blueprint object represents the table in the database. You can use it to change columns as required.

The Schema facade has many useful methods which can be used inside the up() and down() methods. Most of these methods are self-explanatory:

create(string $table, \Closure $callback)
createDatabase(string $name)
disableForeignKeyConstraints()
drop(string $table)
dropDatabaseIfExists(string $name)
dropIfExists(string $table)
enableForeignKeyConstraints()
rename(string $from, string $to)
table(string $table, \Closure $callback)
hasColumn(string $table, string $column)
hasColumns(string $table, array $columns)
dropColumns(string $table, array $columns)
hasTable(string $table)
defaultStringLength(int $length)
registerCustomDoctrineType(string $class, string $name, string $type)
getColumnListing(string $table) 
Click here to learn about the available methods on the Schema builder.

Working with columns

Let's look at how you use table blueprint objects to make columns. First, you create using different methods.

ID column

Laravel has a built-in id() method, which you can use to generate an auto-incremented ID column. The ID column contains int values that uniquely identify the record. A sample code can look like this:

Schema::create('products', function (Blueprint $table) {
            $table->id();
        });

The id method is the same as the method bigIncrements().

Timestamps columns

The timestamps() method generates two columns, create_at, and updated_at. Both these columns are ubiquitous in most web apps. Inside a Schema method, you can use the timestamps() as:

$table->timestamps();

Text columns

Next, we will look at the text(string $name) method used to generate a text column. Some variations of the text column include tinyText() and longText().

See below how these are used:

$table->text('column_name');
$table->tinyText('column_name');
$table->longText('column_name');

Similarly, you can use the following methods:

  • int(string $name)
  • float(string $name [int $precision, [int $scale]])
  • double(string $name, [int $precision, [int $scale]])
  • enum(string $name, array $accepted_values)
  • increments(string $name)
  • time(string $name, $precision)

Column modifiers

When creating columns, you can also use the column modifier methods. The column modifier method will set the attributes and placement of the column. For example, below shows how some of these modifiers are used.

$table->text('type')
    ->nullable() // Sets the column as nullable
    ->after('name') // Places the column after the 'type' column. Similar: first()
    ->default('customer') // Sets the column default to 'customer'
    ->comment('Type of user'); // Adds a comment/description to column

$table->int('reg_number')->autoincrements(); // Sets the column to Auto Increment
For a complete list, visit the Laravel column modifiers docs.

Useful migrations options

When using the migrate command, you have some valuable options to make life easier.

The following command gives you a summary of the executed migrations:

php artisan migrate:status

Result:

+------+---------------------------------------------------+-------+
| Ran? | Migration                                         | Batch |
+------+---------------------------------------------------+-------+
| Yes  | 2014_10_12_000000_create_users_table              | 1     |
| Yes  | 2014_10_12_100000_create_password_resets_table    | 1     |
| Yes  | 2019_08_19_000000_create_failed_jobs_table        | 1     |
| Yes  | 2020_10_15_100535_add_username_to_users_table     | 1     |
| Yes  | 2020_10_15_113440_create_posts_table              | 1     |
| Yes  | 2020_10_15_122016_create_likes_table              | 1     |
| Yes  | 2020_10_15_131806_add_soft_deletes_to_likes_table | 1     |
| Yes  | 2021_07_15_181408_create_products_table           | 1     |
| No   | 2021_07_16_131742_create_testing_table            |       |
| No   | 2021_07_16_131753_create_testing_new_table        |       |
+------+---------------------------------------------------+-------+

Then, to roll back the latest migration operation, use the following command:

php artisan migrate:rollback

Or, you may want to roll back a limited number of migrations. The example below will rollback the last five migrations:

php artisan migrate:rollback --step=5

Alternatively, you may want to roll back all of your migrations. This command will then execute the migrate command, re-create your entire database:

php artisan migrate:refresh

Another typical command is the "migrate:fresh" command. You can use this command to drop all your tables and run all the migrations. Note, however, that this differs from the refresh command. The fresh does not run rollback any changes and drops all tables.

php artisan migrate:fresh

Lastly, you can use the schema dump to create a SQL dump of your database. So, Laravel will store the dump in the database/schema directory of your application. Additionally, you can use the --prune flag to delete the migration files.

This is useful if you want to avoid cluttering your migrations directory. Then the next time you Migrate, this SQL file will be executed first, followed by the migrations. Note, however, this is only if no other migrations have been run.

php artisan schema:dump

You may also be interested in

Source(s):



About the Authors

Anto's editorial team loves the cloud as much as you! Each member of Anto's editorial team is a Cloud expert in their own right. Anto Online takes great pride in helping fellow Cloud enthusiasts. Let us know if you have an excellent idea for the next topic! Contact Anto Online if you want to contribute.

Support the Cause

Support Anto Online and buy us a coffee. Anything is possible with coffee and code.

Buy me a coffee



Leave a Reply

Your email address will not be published. Required fields are marked *