LARAVEL

Laravel to create a table using a migration


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

 

Step 1. Generate a Migration File:

 Use the make:migration Artisan command to generate a new migration file. You can name the migration file based on the purpose of the table you're creating.

php artisan make:migration create_table_name

 

Step 2. Define the Table Schema: 

Open the generated migration file located in the database/migrations directory. In the up() method of the migration class, use the Schema Builder to define the structure of your table.

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

class CreateTableNameTable extends Migration
{
    public function up()
    {
        Schema::create('table_name', function (Blueprint $table) {
            $table->id(); // Creates an auto-incrementing primary key
            $table->string('column1');
            $table->integer('column2');
            $table->timestamps(); // Creates created_at and updated_at columns
        });
    }

    public function down()
    {
        Schema::dropIfExists('table_name'); // Drops the table if the migration is rolled back
    }
}

Replace 'table_name' with the name you want for your table and define the columns as needed. You can use various column types such as string, integer, text, boolean, etc., depending on your requirements.

 

Step 3. Run the Migration:

 Once you've defined your table schema, run the migration using the migrate Artisan command.

php artisan migrate

This command will execute the migration, creating the table in your database based on the schema you defined.

 

Run Single File migration:

If you want to run only a specific migration file, you can use the --path option

php artisan migrate --path=/database/migrations/filename.php

 


LARAVEL