How to make migration in Laravel
Migrations let you easily update your Laravel database - here's how to do it, with an example.
Creating a Migration in Laravel
Migrations in Laravel allow you to define your database structure and modifications using code. This helps ensure that your database is in sync with the application code and makes it easier to keep track of changes and roll back if needed.
Creating a migration in Laravel is very simple. All you need to do is open up the terminal and run the following command:
php artisan make:migration create_table_name
This will create a new migration file located in the database/migrations directory. The file will have a unique timestamp and be named something like create_table_name_2021_01_15_140932_xxxxxx.php. This file contains the following default code:
<?php
use IlluminateDatabaseMigrationsMigration;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateSupportFacadesSchema;
class CreateTableName extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('table_name', function (Blueprint $table) {
//
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('table_name');
}
}
The up() and down() methods are used to define the structure of the table when the migration is run. For example, if we wanted to create a table called "users" with columns for "name", "email", and "password", we can add those fields to the up() method like this:
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->timestamps();
});
}
Once the up() and down() methods have been defined, you can run the migration using the following command:
php artisan migrate
This will create the "users" table in the database and you will now be able to use it in your application.
Migrations are a powerful way to keep your database in sync with your application code and make it easier to track changes. The process of creating a migration in Laravel is very simple and can be done in just a few steps.