Skip to main content
Laravel Basics Tutorial
CHAPTER 08 Beginner

Database Configuration and Migrations

Updated: May 14, 2026
30 min read

# CHAPTER 8

Database Configuration and Migrations

1. Introduction

In core PHP development, if you wanted to create a database table, you opened phpMyAdmin, clicked around the GUI, and manually added columns. If you worked on a team, every developer had to manually recreate the database on their own laptop. It was a nightmare. Laravel solves this with Migrations. Migrations are like "version control" (Git) for your database. In this chapter, we will learn how to build databases entirely through PHP code.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Configure the .env file to connect to MySQL.
  • Generate and read Migration files using Artisan.
  • Use PHP to define database schemas (tables and columns).
  • Execute migrations to automatically build the database.

3. Beginner-Friendly Explanation

Imagine giving instructions to a construction crew to build a house. The old way (phpMyAdmin) is driving to the site, grabbing a hammer, and building the house yourself. If your friend wants the exact same house, they have to come over and copy everything you did manually. Migrations are the Blueprint. You write a blueprint file in PHP that says: "Build a room called 'Users', add a window called 'Email', and a door called 'Password'." You hand the blueprint to the Artisan robot. The robot builds the house instantly. If your friend downloads your code, they give the same blueprint to their robot, and they get the exact same database built on their computer in two seconds.

4. Step 1: Configuration (.env)

Before migrating, Laravel needs to know where the database is. Open your .env file and ensure the credentials match your local MySQL server (XAMPP).
env
123456
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_tutorial_db # Make sure this empty DB exists in phpMyAdmin!
DB_USERNAME=root
DB_PASSWORD=

5. Step 2: Creating a Migration File

We want to create a database table to store Blog Posts. Open your terminal and use the Artisan command:
bash
1
php artisan make:migration create_posts_table

Laravel will create a new file in the database/migrations/ directory. The filename will have a timestamp (e.g., 20240101000000createpoststable.php). The timestamp ensures migrations run in the exact order they were created.

6. Step 3: Writing the Schema

Open the migration file. You will see two methods: up() (what happens when we build) and down() (what happens if we undo the build).

Let's design the posts table:

php
123456789101112131415161718192021222324252627
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up()
    {
        // Schema::create makes a new table called 'posts'
        Schema::create(&#039;posts', function (Blueprint $table) {
            $table->id(); // Creates auto-incrementing Primary Key
            
            $table->string(&#039;title'); // Creates a VARCHAR column
            $table->text(&#039;body');    // Creates a TEXT column
            $table->boolean(&#039;is_published')->default(false);
            
            $table->timestamps(); // Magically creates 'created_at' and 'updated_at' columns!
        });
    }

    public function down()
    {
        // This drops the table if we "rollback" the migration
        Schema::dropIfExists(&#039;posts');
    }
};

7. Step 4: Running the Migration

The blueprint is written. Now we tell the Artisan robot to build it. In your terminal, run:
bash
1
php artisan migrate

Laravel connects to your MySQL database, translates your PHP code into raw SQL, and creates the tables perfectly! If you open phpMyAdmin, you will see your new posts table.

8. Rolling Back (Undoing Mistakes)

If you made a typo (e.g., you spelled 'title' as 'titel'), do not go into phpMyAdmin to fix it! You tell Artisan to undo the last action:
bash
1
php artisan migrate:rollback

Then, you fix the typo in your migration PHP file, and run php artisan migrate again.

9. Best Practices

  • Never Modify Old Migrations: Once a migration has been pushed to a live production server, you *never* edit that file again. If you need to add a new column later, you create a *new* migration (php artisan make:migration addimagetopoststable) that updates the existing table.

10. Common Mistakes

  • SQLSTATE[HY000] [1049] Unknown database: If you run php artisan migrate and get this error, it means you typed DBDATABASE=myapp in your .env file, but you forgot to actually open phpMyAdmin and click "New" to create the blank myapp database first.

11. Exercises

  1. 1. Explain why Migrations are a superior method for database creation when working on a team of developers, compared to manually using a GUI tool like phpMyAdmin.

12. Coding Challenges

  • Challenge: Use Artisan to create a migration for a comments table. Add columns for body (text), userid (integer), and postid (integer). Run the migration.

13. MCQs with Answers

Question 1

What is the primary purpose of Laravel Migrations?

Question 2

Which terminal command executes all pending migration files and physically creates the tables in the MySQL database?

14. Interview Questions

  • Q: Walk me through the purpose of the up() and down() methods in a Laravel migration file.
  • Q: Explain how you would safely add a new column to a table that has already been migrated to a live production database with thousands of users.

15. FAQs

Q: What is the timestamps() method? A: timestamps() is a massive time-saver. By adding it to your migration, Laravel automatically creates a created
at and updated_at column in your table. Whenever you insert or update data using Laravel's ORM, Laravel updates these timestamp columns automatically!

16. Summary

In Chapter 8, we treated our database infrastructure like code. Migrations allow us to design complex databases entirely in PHP. By writing programmatic blueprints and executing them via the Artisan CLI, we ensure our database structure is perfectly reproducible across any developer's laptop and safe to deploy to production servers.

17. Next Chapter Recommendation

We have the tables built. Now we need to put data into them. Proceed to Chapter 9: Eloquent ORM Basics to learn the most powerful feature in Laravel.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·