How to Use Migrations in Laravel 9?

Laravel 9 provides us the concept of migration to deal with database operations. For example you made an entire Laravel project on your local machine and now you want to migrate that over to Live server. Imagine you have to create everything in database again for the live server. But Laravel 9 provides us an easy way to handle that.

We will create every table by running migration commands. It is easy an syntax and just one time effort. Once everything is done locally you would just need to run the command once over to your live server and that is it. So let’s start.

1. Installing Laravel 9

First we need to install Laravel 9 by running this command.

composer create-project --prefer-dist laravel/laravel shop-app

2. Database Configuration

In order to configure the database we need to add these credentials in my .env file.

  • Database name
  • Database password
  • Database username
  • Database host

In order to do so, we will add the following lines in the .env file.

DB_HOST=localhost 
DB_DATABASE=shop-app-db 
DB_USERNAME=root 
DB_PASSWORD=secret

3. Creating Product Model and Migration

Here we are dealing with products which we will sell so we will create Product model and with that a migration. We will run this command. 

php artisan make:model Product -m

This will create a model as app/Product.php. Add this code in model file. 

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    protected $fillable = ['name', 'price', 'description', 'category_id'];
}

Here name, price and description are usual fields with category_id is foreign key to other table which is category. This means every product will have a category. It is very easy to implement in Laravel 9. Now moving to migration. Check your database/migrations folder. There you will see CreateProductsTable class. file name may change but in the end it will be “…_create_products_table.php”. Place this code in there.

<?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->string('name');
            $table->float('price');
            $table->text('description');
	    $table->bigInteger('category_id')->unsigned();
            $table->timestamps();
        });
    }

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

4. Creating Category Model and Migration

Now we will create Category model with migration by running this command on root. 

php artisan make:model Category -m

This will create app/Category.php and we need to place this code there. 

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    protected $fillable = ['name'];
}

and now need to check database/migrations folder and find “…_create_categories_table.php” as ending name of migration file. We need to put this code in migration file. 

<?php

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

class CreateCategoriesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('categories', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->timestamps();
        });
    }

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

5. Establishing category_id as foreign key

Now we need to create the migration which will establish category_id as foreign key to categories’ table. For this run following command to create new migration. 

php artisan make:migration make_category_id_foreign_key

A new migration will be created in database/migrations folder. Add this code in there. 

<?php

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

class MakeCategoryIdForeignKey extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('products', function (Blueprint $table){
        	$table->foreign('category_id')->references('id')->on('categories');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        //
    }
}

5. Running Migration

Now run this command to create tables.

php artisan migrate

6. Some other commands

There are some other important Laravel 9 migration commands.  This is the command to run migrations with seeder. 

php artisan migrate --seed

This will create migrations table in database to keep track of migrations which we have run. when we run migrate command it runs in background.

php artisan migrate:install

This command to rollback all migrations which we have ran on this instance. 

php artisan migrate:reset

This is the command to rollback every migration and then running every available migration again. It is like running reset and then migrate. 

php artisan migrate:refresh

Next command will delete all the tables and then runs every migration again. It is same as refresh but it doesn’t bother with “down” migrations. It just deletes the tables and then runs the “up” migrations again. 

php artisan migrate:fresh

Next command will rollback every migration till the last instance you ran migrations or you can add number of migrations to rollback with –step=n option.

php artisan migrate:rollback

Next command will tell use status of every migration with Y or N showing us whether we have run this migration or not.

php artisan migrate:status

Now whenever we need to create a database on live or development server we only need to run this command and it will create database with same structure as local on live or development server. I hope you understand how easy it is to use migrations in Laravel 9. If you face any problems please leave a comment.