Swiftorial Logo
Home
Swift Lessons
AI Tools
Learn More
Career
Resources

Migrations in Laravel

What are Migrations?

Migrations are a type of version control for your database in Laravel. They allow you to define the structure of your database tables using PHP code, making it easy to share your database schema with others and keep track of changes over time.

Creating a Migration

To create a new migration, you can use the Artisan command line tool. The command is as follows:

php artisan make:migration create_users_table

This command will create a new migration file in the database/migrations directory. The file name will include a timestamp followed by the name you provided.

Editing a Migration

Once you have created a migration, you can edit it to define the structure of the table. A typical migration file might look like this:

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateUsersTable extends Migration
{
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('users');
    }
}
                

The up method is used to define the columns in the table, while the down method should reverse the operations defined in the up method.

Running Migrations

To apply the migrations and create or modify tables in your database, you use the following command:

php artisan migrate

This will run all of the pending migrations. If you want to rollback the last migration, you can use:

php artisan migrate:rollback

Checking Migration Status

To see a list of all migrations that have been executed, you can run:

php artisan migrate:status

This command will show you which migrations have been applied and which are still pending.

Seeding Your Database

After creating migrations, you may want to populate your tables with some initial data. This can be done using seeders. You can create a new seeder with the following command:

php artisan make:seeder UsersTableSeeder

Then, in your seeder file, you can define how to populate the table:

use Illuminate\Database\Seeder;
use App\Models\User;

class UsersTableSeeder extends Seeder
{
    public function run()
    {
        User::create([
            'name' => 'John Doe',
            'email' => 'john@example.com',
        ]);
    }
}
                

To run the seeder, you can use:

php artisan db:seed --class=UsersTableSeeder

Conclusion

Migrations are a powerful feature in Laravel that allow you to manage your database schema effectively. By using migrations, you can ensure that your database is structured correctly and is easily shareable among team members. Always remember to keep your migrations organized and comment your code for better maintainability.