How to Create Table in Laravel Using Migration

AuthorSumit Dey Sarkar

Pubish Date22 Mar 2023

categoryLaravel

In this tutorial we will learn how to create table in laravel using migration.

 

How to Create Table in Laravel Using Migration

To create a table in Laravel using migration, you can follow these steps:

 

Step 1 - Open your command prompt or terminal and navigate to your Laravel project directory.

 

Step 2 - Type the following command to create a new migration file:

php artisan make:migration create_table_name

Make sure to replace table_name with the name you want to give to your table.

 

Step 3 - Open the newly created migration file inside the database/migrations folder. In the up() method of the file, you can define the schema of your table using Laravel's schema builder.

For example, to create a users table with id, name, email, and password columns, you can use the following code:

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->string('email')->unique();
        $table->string('password');
        $table->timestamps();
    });
}

 

Step 4 - In the same migration file, add the reverse schema definition to the down() method. This method will be used to roll back the migration.

For example, to drop the users table, you can use the following code:

public function down()
{
    Schema::dropIfExists('users');
}

 

Step 5 - Finally, run the migration by typing the following command in the terminal:

php artisan migrate

This will create the users table in your database.

You can also add more columns to the table by using Laravel's schema builder. For more information, you can refer to Laravel's documentation on migrations.

Comments 0

Leave a comment