How to Create and Run Migrations in Laravel 11

To create and run migrations in Laravel 11, you can follow these steps:

Step 1: Create a Migration

To create a migration, you can use the Artisan command-line tool provided by Laravel. Open your terminal and run the following command:

php artisan make:migration create_table_name --create=table_name

Replace table_name with the name of the table you want to create and create_table_name with a descriptive name for your migration file.

Step 2: Define Schema

Once the migration file is created, open it in your code editor. In the up method, define the schema for your table using the Schema Builder:

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();
            $table->string('column_name');
            // Add more columns as needed
            $table->timestamps();
        });
    }

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

Step 3: Run Migrations

To run your migrations and create the table in your database, use the following command:

php artisan migrate

Step 4: Rollback Migrations (Optional)

If you need to rollback your migrations, you can use the following command:

php artisan migrate:rollback

This command will rollback the latest migration. If you need to rollback a specific number of migrations, you can use the --step option:

php artisan migrate:rollback --step=2

Conclusion

Migrations in Laravel are an efficient way to manage your database schema. By following these steps, you can create and run migrations effortlessly, ensuring that your database schema stays in sync with your application’s code. This makes it easy to collaborate with other developers and deploy your application across different environments.

Leave a Reply