How to run database migrations in Laravel



Image not found!!

In Laravel, database migrations are used to version control your database schema and easily share it with your team. Laravel provides a convenient Artisan command-line tool to help you create and run migrations.

Here's a step-by-step guide on how to run database migrations in Laravel:

Step 1: Create a Migration

se the following Artisan command to create a new migration file:

php artisan make:migration your_migration_name

This will create a new migration file in the database/migrations directory.

Step 2: Define Schema in the Migration File

Open the generated migration file (located in database/migrations) and define the schema for your database table. You can use the up method to specify the changes you want to make to the database:

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

Step 3: Run the Migration

To run the migration and apply the changes to the database, use the following Artisan command:

php artisan migrate

This command will execute all pending migrations.


Additional Commands:

  • To rollback the last database migration, you can use:
php artisan migrate:rollback
  • To rollback all database migrations:
php artisan migrate:reset
  • If you want to refresh the database and re-run all migrations, you can use:
php artisan migrate:refresh

These commands are useful during development or when you need to reset your database to a clean state.

Remember to replace your_migration_name and your_table_name with appropriate names for your migration.

Database migrations are a crucial part of Laravel's database management, making it easy to version-control and collaborate on your database schema changes.



=== Happy Coding