DEV Community

Cover image for Laravel Migrations: Asekhame's Beginner's Guide πŸš€
Asekhame Joel
Asekhame Joel

Posted on

Laravel Migrations: Asekhame's Beginner's Guide πŸš€

What Are Migrations in Laravel? πŸ€”

Migrations in Laravel are like a set of instructions for your database. They help you create, update, or delete tables and columns without having to manually do it each time. Think of it like a way to keep track of changes to your database, so you can easily update it across different environments or share your changes with a team. Instead of editing the database directly, you write a migration, run it, and Laravel takes care of the rest!

Key Benefits of Migrations

β€’ Code-Driven Database Management: No need to open database editors. Define changes in code and let Laravel do the rest.

β€’ Collaboration-Friendly: Share migration files with teammates for a synchronized database structure.

β€’ Track Database Changes: Easily roll back or apply changes across environments (local, staging, production).

In essence, migrations simplify and standardize how PHP developers work with databases, making it a vital tool in any Laravel project.

Why Should You Use Migrations? πŸ› οΈ

  1. Efficient Teamwork πŸ‘¨β€πŸ’»πŸ‘©β€πŸ’»: Imagine working with a team of developers who all need the same database structure. Instead of manually creating tables or columns and risking inconsistencies, you share a migration file. When the team runs it, everyone’s database is in sync.

2.Version Control πŸ“œ:
Migrations log every change made to the database. Need to undo a change? Simply roll back using the php artisan migrate:rollback command.

3.Automation βš™οΈ:
Save time by avoiding manual database edits. A single command like php artisan migrate applies all pending migrations.

*How Do Migrations Work in Laravel? 🚧 *

  1. Migration Files πŸ“‚:
    Migration files are PHP scripts stored in the database/migrations directory. Each file corresponds to a specific database change. Each file represents a specific change to the database (e.g creating a table, adding a column). The Migrations Files are timestamped to ensure they execute in the correct order.

  2. The Structure of a Migration File πŸ“œ:
    Every migration file contains two core methods:

    β€’ up(): Defines the changes to be applied to the database (e.g., creating or modifying tables).
    β€’ down(): Reverses the changes made in the up() method, allowing for rollbacks.

Example: A Basic Migration File

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');
    }
}
Enter fullscreen mode Exit fullscreen mode

3.Commands to Manage Migrations ⚑:
Laravel provides artisan commands to manage migrations effectively:

β€’ Generate a Migration File:
php artisan make:migration create_table_name

Example: php artisan make:migration create_users_table

This command creates a new migration file in the database/migrations folder in your laravel project.

β€’ Run Migrations:
php artisan migrate
This command applies all pending migrations and updates your database(e.g creates tables or add column), in otherwords Running migrations through the command php artisan migrate will modify your database by creating tables or adding columns. Create a migration with php artisan make:migration create_posts_table, edit the migration file and define the table structure in the up method, then run php artisan migrate to apply this migration to your database.

β€’ Rollback Migrations:
php artisan migrate:rollback
this command Reverses the last migration(s) you applied, If you made a mistake in your last migration and need to undo it an example of this is when You added a column but realized it was wrong. Rollback removes it

β€’ Refresh Migrations:
php artisan migrate:refresh
Only useful during development. The command Deletes all tables and runs all migrations again, if you’ve made lots of changes and want to rebuild the database fresh, an example of this is when Your database is messy during testing, so you clean it up and rebuild it.
Note: It deletes all your data from your database

Quick Table of Commands
php artisan make:migration - Creates a new migration file.
php artisan migrate -Runs all pending migrations.
php artisan migrate:rollback - Undoes the last migration(s).
php artisan migrate:reset - Undoes all migrations (clears the database).
php artisan migrate:refresh - Deletes all tables and re-runs migrations.
php artisan migrate:status - Shows migration status (applied or not).
php artisan migrate --seed - Runs migrations and seeds the database.
php artisan migrate --force - Runs migrations in production without confirmation.

Final Thoughts πŸ’‘

For PHP developers, managing databases is a routine task. With Laravel migrations, you can significantly streamline and automate this process. You won’t need to visit your database interface as often, and you’ll enjoy the added benefits of version control, teamwork, and efficiency. Whether you're creating tables, adding columns, or rolling back changes, migrations are your best friend.
Embrace migrations, and say goodbye to messy database management forever! 🌟

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free β†’

πŸ‘‹ Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay