Migrations are generally used to modify the database schema. Along with Laravel’s schema builder, it builds the application’s database schema. Designing tables not only become easy with the use of migrations, but the entire table can also be created.
Migrations are stored in : database/migrations
- Generate Migration:
Make:migration – This command is used to generate a migrationphp artisan make:migration sample_table
This will generate a migration with the name SampleTable
- Migration Structure
It contains two methods: up and down.
New columns, tables or indexes are added to the database using the up method.
The operations performed by the up method are reversed by the down method.<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class SampleTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { // } /** * Reverse the migrations. * * @return void */ public function down() { // } }
- Running Migration
php artisan migrate – this command is used to run the migration.
This will create the migration and insert an entry into the migration table. - RollBack a Migration
php artisan migrate:rollback – This command is used to rollback a migration - Drop All Tables & Migrate
php artisan migrate:fresh – This command is used to drop all the tables in the database.
Tables
- Create Table
Create method is used to create a new database table on the Schema facade. It accepts two arguments.- The name of the table
- Blueprint object – Used to define the new table:
Schema::create(‘sample_table’, function (Blueprint $table) {
$table->increments(‘id’);
});
- Rename a Table
To rename an existing method use rename methodSchema::rename($from, $to);
- Drop a Table
To drop the table use drop or dropIfExists method.Schema::drop('sample_table'); or Schema::dropIfExists('sample_table');
Run a specific migration
We will create sample_table with some columns:
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class SampleTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('sample_table', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('name'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('sample_table'); } }
To run only this migration we need to add the path of this migration in migrate command
php artisan migrate –path=/database/migrations/2019_04_08_121257_sample_table.php
With this, we can run a specific migration.
The table is created along with the fields.