Explanation of Database Migrations in Laravel 5.8

Migration is a way that allows us to create a table in our database, without accessing the database manager such as phpmyadmin or sql lite.

To create a migration we should execute the command:

php artisan make:migration [options] [--] <name>

Here, in the option we have number options to enter depending upon the requirement. We can see all the options given below:

–create[=CREATE]The table to be created
–table[=TABLE] The table to migrate
–path[=PATH] The location where the migration file should be created
–realpath Indicate any provided migration file paths are pre-resolved absolute paths
–fullpath Output the full path of the migration
-h, –help Display this help message
-q, –quiet Do not output any message
-V, –version Display this application version
–ansi Force ANSI output
–no-ansi Disable ANSI output
-n, –no-interaction Do not ask any interactive question
–env[=ENV] The environment the command should run under
-v|vv|vvv, –verbose Increase the verbosity of messages: 1 for normal output, 2 for more verbose output and 3 for debug

Once we create the migration we can see a file under Migration-> database. Migrations are files which contain a class definition with both an up() and a down() method. The up() method helps to apply changes to the database and the down() method is used to rollback the changes in the database.

Example:-

class CreateCustomersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('customers', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('customers');
    }
}

To run all of our outstanding migrations, we can execute the Artisan command given below:

php artisan migrate

Also once we execute our migrations in the database we do have the option to roll back the latest migration operation, by using the rollback Artisan command. This command rolls back the last “batch” of migrations, which may include multiple migration files:

php artisan migrate:rollback

In Laravel we also have an option to rollback and execute the migration simultaneously with an Artisan command:

php artisan migrate:refresh

To see a video for the topic you can follow the video given below:-

Follow the other blog in which we will learn about creating tables in the database.

Tagged : / /