Laravel is one of the most popular PHP frameworks due to its simplicity and advanced features in web development. One of the very significant possibilities of Laravel is the use of the migration system for managing databases. This system allows developers to easily make structural changes in their own databases and transfer these changes to other teams.
Migrations in Laravel are defined as PHP classes that are stored in the database/migrations
directory. Each migration contains two main methods: up
and down
. The up
method is used to add or modify a table, and the down
method is used to revert to the previous settings.
Working with migrations in Laravel has many benefits, such as: change history management, the ability to rollback changes, and continuous process development. Development teams can record changes in the database using the artisan migrate
command and revert versions using artisan migrate:rollback
.
For example, you can use the following command to create a new migration to create a table named "users":
php artisan make:migration create_users_table
Next, you can implement the necessary changes in the created migration file:
<?php
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->string('password');
$table->timestamps();
});
}
public function down()
{
Schema::dropIfExists('users');
}
}
After writing the migration, to execute it in the database, use the following command:
php artisan migrate
Now, let’s review what this code does:
<?php
: start of the PHP fileuse Illuminate\Database\Migrations\Migration;
: importing the base migration classuse Illuminate\Database\Schema\Blueprint;
: importing Blueprint for table creationuse Illuminate\Support\Facades\Schema;
: importing the Schema facade for database interactionsclass CreateUsersTable extends Migration
: starting to define a migration class named CreateUsersTablepublic function up()
: the method used when running the migration to implement changesSchema::create('users', function (Blueprint $table)
: defining a new table named users$table->id();
: adding an ID column as the primary key$table->string('name');
: defining a column for storing the user's name$table->string('email')->unique();
: defining an email column which must be unique$table->string('password');
: defining a column for storing the password$table->timestamps();
: adding default timestamp columns for created and updated timespublic function down()
: the method used for rolling back the migration to remove changesSchema::dropIfExists('users');
: dropping the users table if it exists