LARAVEL

Laravel Migration Introduction


In Laravel, migrations are a feature that allows you to manage your database schema and perform database operations in a version-controlled manner. Migrations are written in PHP and are stored in the database/migrations directory of your Laravel project.

 

Why Use Migrations?

  • Version Control: Migrations provide a convenient way to version control your database schema changes along with your application code.
  • Consistency: With migrations, you can ensure that all developers working on a project have the same database schema structure.
  • Rollbacks: Laravel allows you to roll back migrations, reverting changes made to your database, which can be extremely useful during development or when deploying updates.

 

Step to Work with migration's

 

step 1 . Creating a Migration

You can create a new migration using the php artisan make:migration Artisan command. For example, to create a migration for creating a new table, you would run:

php artisan make:migration create_users_table

This command will create a new migration file in the database/migrations directory with a timestamp prefix and the provided name.

 

step 2 . Writing Migration Files

Once you have created a migration file, you can open it and define the database schema changes you want to make using Laravel's Schema Builder. For example, to create a users table, you can define the table schema in the up method:

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

class CreateUsersTable extends Migration
{
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }

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

In the down method, you define how to reverse the changes made by the migration. In this case, it drops the users table.

 

step 3 . Running Migrations

To run all pending migrations, you can use the migrate Artisan command:

php artisan migrate

This will execute all the migrations that haven't been run yet.

 

step 4 . Rolling Back Migrations

To roll back the last migration operation, you can use the migrate:rollback Artisan command:

php artisan migrate:rollback

This will revert the last migration that was run.

Note - Laravel migrations provide a powerful and convenient way to manage your database schema. By using migrations, you can easily version control your database changes, ensure consistency across environments, and easily roll back changes if needed.


LARAVEL