what is migration

Table of Contents

1. What are Migrations?. 1

2. Why are Migrations Created?. 1

Sharing Databases in a Team Environment: Laravel Migrations Approach. 2

Creating Tables Directly: 2

Using Laravel Migrations: 2

How to use Migration in Laravel?. 2

1. Creating Migrations: 2

2. Editing Migration Files: 2

3. Running Migrations: 2

How to Add a New Column in Existing Migration. 5

Why we use rollback in migration?. 5

What are seeder and factories in Laravel?. 6

Seeder: 6

Factories: 6

What is the difference between rollback, fresh and refresh migration commands?. 7

Rollback: 7

Fresh: 7

Refresh: 7

In summary: 7

Conclusion. 8

FAQs. 8

In Laravel, migrations play a very important role in managing database schema changes. Let's delve into why migrations are created, their purpose, the commands associated with them, and how they work.

1. What are Migrations?

Migrations are like version control for your database, allowing you to modify your database schema over time. They provide an efficient way to update, roll back, and share changes with others. Laravel migrations are written in PHP and are database-agnostic, meaning you can use the same migration code for different database systems.

2. Why are Migrations Created?

Migrations are created to streamline the process of evolving the database structure as your application develops. Whether you're adding a new table, modifying an existing one, or deleting columns, migrations ensure that these changes are applied consistently across different environments.

Sharing Databases in a Team Environment: Laravel Migrations Approach

When collaborating within a large team, efficient database sharing is crucial. Two common methods are creating tables directly in the database or using Laravel migrations to ensure consistency. Let's explore both approaches:

Creating Tables Directly:

Advantages:

  1. Quick and straightforward.
  2. Suitable for smaller projects or immediate needs.

Disadvantages:

  1. Prone to inconsistencies if team members manually manage their databases.
  2. Lack of version control for database changes.

Using Laravel Migrations:

Advantages:

  1. Migrations keep track of database changes in a version-controlled way.
  2. They allow us to work collaboratively, ensuring everyone has the same database structure.
  3. Changes made to the database can be easily rolled back or moved forward.

How to use Migration in Laravel?

Let's now take a look at migration commands used in our Laravel project. We'll explore how to create migrations and use them to create tables in the database.

In Laravel, migrations are a way to manage database changes. They help create tables and alter their structures. Here's how we use migration commands in our project:

1. Creating Migrations:

Laravel provides a simple command to make a new migration. For example,

php artisan make:migration CreateUsersTable

generates a new migration file for creating a users table.

2. Editing Migration Files:

Open the generated migration file in the "database/migrations" directory. Here, you define the structure of your table using Laravel's schema builder.

3. Running Migrations:

Once your migration file is ready, run php artisan migrate. This command executes all pending migrations and creates the specified tables in the database.

Example:

Let's say we want to create a migration for a "posts" table. We run

php artisan make:migration CreatePostsTable

The above command make a file name like this

2023_11_27_100530_create_post_table.php

the migration command will automatically add “_” in CreatePostsTable word and this file is located in database/migrations.

php artisan migrate 

the above command will apply the changes in the database.

If we want to create a model using an artisan command and also want to generate a table for that model in the database, we can use the below command:

php artisan make:model Post -m

This command does two things for you. It creates a model named "Post," and it generates a migration file for the "posts" table associated with that model. You can find this migration file in the "database/migrations" directory. This makes it convenient to define the structure of the "posts" table and apply changes to the database seamlessly.

When you create a migration for the "posts" table using the artisan command, the structure of the migration file would typically look something like this:

<?php

use Illuminate\Database\Migrations\Migration;

use Illuminate\Database\Schema\Blueprint;

use Illuminate\Support\Facades\Schema;

class CreatePostsTable extends Migration

{

    /**

     * Run the migrations.

     *

     * @return void

     */

    public function up()

    {

        Schema::create('posts', function (Blueprint $table) {

            $table->id();

            $table->string('title');

            $table->text('content');

            $table->timestamps();

        });

    }



    /**

     * Reverse the migrations.

     *

     * @return void

     */

    public function down()

    {

        Schema::dropIfExists('posts');

    }

}

In the above post migration file structure:

  1. up Function: The up function is responsible for defining the changes you want to apply to the database when running the migration.
    In this example, it creates the "posts" table with specified columns using the Schema::create method.
  2. down Function: The down function is used to define the actions to be taken when rolling back the migration.
    In this case, it drops the "posts" table if the migration needs to be rolled back using the Schema::dropIfExists method.
  3. The id method creates an auto-incrementing primary key.
  4. title is a string column to store the title of the post.
  5. content is a text column to store the content of the post.
  6. timestamps method automatically adds created_at and updated_at columns to track creation and modification times.

Of course, you can customize this structure based on your specific requirements for the "posts" table. Once you define the structure, you can run the migration to apply these changes to your database and if you want to check the datatypes, which you can use in the migration up function while adding the columns, then you can visit Laravel migration datatypes section.

How to Add a New Column in Existing Migration

Certainly! If you forget to add a new column to an existing table in a migration or need to modify the structure later, you can use the following migration command:

php artisan make:migration add_column_to_table_name --table=table_name
  1. add_column_to_table_name: Replace this with a meaningful name for your migration, indicating that it adds a column.
  2. --table=table_name: Specify the name of the table to which you want to add a new column.

This command will generate a new migration file in the database/migrations directory. Open the generated migration file, and in the up method, you can add the new column using the addColumn method. For example:

public function up()

{

    Schema::table('table_name', function (Blueprint $table) {

        $table->string('new_column');

    });

}

After making these changes, you can run the migration to apply the new column to the existing table:

php artisan migrate

This way, you can easily add new columns or make modifications to an existing table structure using Laravel migrations.

Why we use rollback in migration?

Suppose you have created a migration and create a table in the database with the help of that migration, then If you want to rollback (undo) a specific migration in Laravel, you can use the following command

php artisan migrate:rollback --step=1

--step=1: This option specifies the number of batches to rollback. In this case, it's set to 1, meaning it will rollback the last batch of migrations.

php artisan migrate:rollback

By default, the migrate:rollback command rolls back the last batch of migrations. If you want to rollback more batches, you can adjust the --step option accordingly.

After running this command, Laravel will undo the changes made by the specified migration, effectively rolling back the database to its previous state before that migration was applied.

What are seeders and factories in Laravel?

In Laravel, Seeder and Factories are tools used for database seeding, which means populating your database with sample or default data for testing or development purposes.

Seeder:

Definition: A seeder is like a gardener for your database. It's a class in Laravel that helps you insert specific data into your database tables. You define what data you want, and the seeder plants it in your tables

///Example Seeder (database/seeders/DatabaseSeeder.php):

<?php
use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder

{

    public function run()

    {

        $this->call(UserSeeder::class);

        // Additional seeders...

    }

}

?>

Use: Seeders are particularly useful for adding initial or default data to your tables. For example, you might use a seeder to create an admin user or populate a countries table with a list of countries.

Factories:

Definition: Factories are like data factories. They provide a way to generate fake or test data quickly. You define a blueprint for the kind of data you want, and Laravel's factories can create instances of that data on the fly.

<?php

use Illuminate\Database\Seeder;

use App\Models\User;

class UserSeeder extends Seeder

{

    public function run()

    {

        \App\Models\User::factory(10)->create();

    }

}

?>

Use: Factories are beneficial when you need a variety of data for testing. For instance, if you're testing a blog application, you might use a factory to create multiple fake blog posts with different titles and content for testing purposes.

In the above seeder and factories example, the UserFactory defines the structure of a user, and the UserSeeder uses the factory to create 10 user records.

To run the seeders, you would use the

php artisan db:seed

If you want to refresh the database and re-run all seeders, you can use

php artisan migrate:refresh --seed

In simple terms, seeders help you plant specific data, while factories help you create lots of test data easily. Both are handy tools when you're setting up or testing your Laravel application.

What is the difference between rollback, fresh and refresh migration commands?

In Laravel, the rollback, fresh, and refresh migration commands serve different purposes:

Rollback:

php artisan migrate:rollback

The rollback command is used to undo the last batch of migrations that were run. It essentially reverts the database to the state it was in before the last migration batch was applied.

Fresh:

php artisan migrate:fresh

The fresh command is more aggressive. It rolls back all migrations and then re-runs them, effectively resetting the entire database. It is useful when you want to start with a clean slate and rebuild the entire database from scratch

Refresh:

php artisan migrate:refresh

The refresh command is a combination of rollback and fresh. It rolls back all migrations, runs the migrate command to reapply them, and then runs the --seed option if seeding is specified. It's like refreshing the database to its initial state with the advantage of reseeding the database with sample data.

In summary:

rollback: Undoes the last batch of migrations.

fresh: Resets the entire database, rolling back and reapplying all migrations.

refresh: Rolls back and reapplies all migrations, optionally reseeding the database.

Conclusion

In conclusion, migrations in Laravel are for managing database schema changes efficiently. Serving as a version control system for your database, migrations facilitate seamless updates, rollbacks, and collaborative work. Written in PHP and database-agnostic, they offer a consistent approach to modifying your database structure over time.

The choice between creating tables directly in the database and using Laravel migrations becomes apparent when working in a team environment. While direct table creation is quick, Laravel migrations provide version control, ensuring a shared and consistent database structure, making collaboration smoother.

The process of using migrations involves creating, editing, and running them. Laravel simplifies this with commands like make:migration and migrate, enabling developers to define table structures effortlessly.

Seeders and factories play pivotal roles in database seeding, allowing for the insertion of specific or test data. Seeders help plant tailored data, while factories generate diverse test data, both essential tools for application setup and testing.

Commands like rollback, fresh, and refresh serve distinct purposes. Rollback undoes the last batch of migrations, fresh resets the entire database, and refresh combines rollback and fresh, providing a comprehensive solution.

In essence, Laravel migrations, coupled with seeders and factories, offer a robust framework for evolving database structures, ensuring consistency, version control, and efficient collaboration in development projects.

FAQs

Q: What is the purpose of Laravel migrations?

A: Migrations in Laravel serve as version control for databases, allowing efficient modification of the database schema over time.

Q: Why are migrations created?

A: Migrations streamline the process of evolving the database structure as your application develops, ensuring consistency across different environments.

Q: How do Laravel migrations support team collaboration?

A: Migrations facilitate efficient database sharing in a team environment, ensuring consistent database structures and version-controlled changes.

Q: What are the advantages of creating tables directly in the database?

A: Quick and straightforward setup; suitable for smaller projects or immediate needs.

Q: How does using Laravel migrations benefit team collaboration?

A: Migrations keep track of changes in a version-controlled way, ensuring a collaborative and consistent approach to database modifications.

Q: What commands are used for Laravel migrations?

A: Key migration commands include php artisan make:migration, php artisan migrate, and php artisan make:model [ModelName] -m.

Q: How do you create a migration for a new table?

A: Use the command php artisan make:migration CreateTableName.

Q: What does the up function in a migration file do?

A: The up function defines the changes to apply to the database, such as creating a new table with specified columns.

Q: How can you add a new column to an existing migration?

A: Use the command php artisan make:migration add_column_to_table_name --table=table_name and then define the new column in the generated migration file.

Q: Why would you use the rollback command in Laravel migrations?

A: The rollback command is used to undo the last batch of migrations, effectively reverting the database to its state before the last migration.

Q: What is the purpose of database seeding in Laravel?

A: Seeder classes help you insert specific data into your database tables, often used for adding initial or default data for testing or development purposes.

Q: How do factories differ from seeders in Laravel?

A: Factories generate fake or test data quickly, providing a blueprint for data creation, while seeders insert specific data into tables.

Q: What is the difference between Laravel migration rollback, fresh, and refresh commands?

A: The rollback undoes the last batch of migrations, fresh resets the entire database, and refresh combines rollback and fresh, effectively resetting the database while optionally reseeding it.

Q: Can you rollback more than one batch of migrations?

A: Yes, you can specify the number of batches to rollback using the --step option, for example, php artisan migrate:rollback --step=2.

Q: How does the Laravel migrate:refresh command differ from migrate:fresh?

A: The migrate:refresh command combines rollback and migrate, while migrate:fresh rolls back all migrations and then re-runs them without reseeding.

1 Comments

  • shaheryar bhatti

    shaheryar bhatti

    27 Nov 2023 12:28
    Thanks guys! let us know if you have any question.

Post Comment