n3s0 || journal

Creating, Migrating, and Resetting Migrations on Laravel Framework

Posted on 2 mins

Laravel Php Devel

Overview

Something that I tend do is forget how to crate migrations in the Laravel PHP Framework.

Migrations within Laravel act as version control for your applications database. They can also act as a database agnostic method in which the database schema can be configured.

This is also useful should there be the need to make a small change to a database for a database table.

Migration Generation

Migrations can be built manually. But, there’s actually a better method. The artisan command can be used to create the migration file. Which acts as a scaffold or template for the base for the file.

From this file, the following attributes for the database can be configured.

Below is the Artisan command for generating a migration for the database.

php artisan make:migration create_migration_table

This will create a new migration file with the date and the migration name specified. These files will be located in the relative path database/migrations in the project directory.

Below is an example of a migration file. This one was plulled from the Laravel documentation for migrations. This is a migrations file created for a table named flights.

Configuring the migration consists of adding the appropriate code to the up() and down() functions.

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

Performing Migrations

This section provides the command for migrating the database.

php artisan migrate

Should there be a need to check the migration status the following command is available.

php artisan migrate:status

Rollback Migrations

To sometimes there’s a need to fix your changes but, resetting the database isn’t an option. To do this, the rollback command can be used.

php artisan migrate:rollback

There are also times where rolling back all of the database migrations is required. The reset command will perform this action.

php artisan migrate:reset

References

Below are references to the sites utilized to assist with creating this article.