Hello World, Welcome to my website. Today I am going to discuss how to use database migration in laravel. For a better understanding of database migration, I have created this tutorial with example.
I have divided this tutorial into the following parts.
- What is migration?
- How to Create a migration file?
- How to Run Migration?
What is migration?
Migration is a file which Creates or modify the database tables.
Migration Up Method
Whenever new migration created then the system grabs this migration and run the up method. it helps to do the things.
Migration Down Method
If someone wants to roll back his most recent set of migrations then down method will run by the system. It helps to undo the things.
Laravel comes with “create user table” migration. Following is the code of this migration file.
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateUsersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('users', function (Blueprint $table) { $table->increments('id'); $table->string('name'); $table->string('email')->unique(); $table->timestamp('email_verified_at')->nullable(); $table->string('password'); $table->rememberToken(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('users'); } }
In the above code, you can see that the up method is creating the table and defining columns in this table and down method drop this table.
Please define your database credentials in .env file
How to Create migration a file?
Laravel has lots of command-line tools for working with the app and generate files. In these commands, One command allows creating the migration file. For example, we want to create the above the user table. We will run the following command to create a migration file.
php artisan make:migration create_users_table
The above command can accept two following flags.
- –create=table_name
This flag will create a table. This flag auto-set when creating a migration.
- –table=table_name
This flag will do modification the existing table.
Here are a few examples:
php artisan make:migration create_users_table
php artisan make:migration add_votes_to_users_table --table=users
php artisan make:migration create_users_table --create=users
How to Run Migration?
We have created a migration file. Now, Its time to run this migration file. The following command will run the migration and create users table in the database.
php artisan migrate
When we run the above command, It will create a similar filename like following.
2014_10_12_000000_create_users_table
I hope you are enjoying my tutorials. Please give your feedback in the comment section. 🙂 🙂