How to Create, Run & Rollback Migration in Laravel 11?

By Hardik Savani April 16, 2024 Category : Laravel

Hi devs, I'll show you how to create a migration in Laravel 11. We'll learn how to make a database table using migration in Laravel 11.

I'll guide you through creating a database table using Laravel migration. We'll use Laravel 11 commands to make a migration for the table.

In this example, we'll simply create a "posts" table with columns for id, title, body, is_published, created_at, and updated_at. We'll generate a new migration using Laravel 11 command and add the specified columns. Then, we'll run the migration, and a table will be created in the MySQL database. Let's check out the tutorial below.

laravel 11 database migration

Create Migration:

Using the command below, you can easily create a migration for a database table.

php artisan make:migration create_posts_table

After running the above command, you can see a newly created file below. You have to add a new column for string, integer, timestamp, and text data types as shown below:

database/migrations/2024_03_21_133331_create_posts_table.php

<?php
   
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
    
return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->text('body');
            $table->boolean('is_publish')->default(0);
            $table->timestamps();
        });
    }
    
    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('posts');
    }
};

Run Migration:

Using the below command, we can run our migration and create a database table.

php artisan migrate

After that, you can see the newly created table in your database as shown below:

laravel 11 migration output

Create Migration with Table:

You can create a new migration by defining the table name.

php artisan make:migration create_posts_table --table=posts

Run Specific Migration:

You can run a specific migration using the command below:

php artisan migrate --path=/database/migrations/2024_03_21_064006_create_posts_table.php

Migration Rollback:

You can rollback a migration using the following command:

php artisan migrate:rollback

I hope it can help you...

Shares