Learn Laravel Β· 5/17

Database & Migrations: Building Your Data Structure

6 min read

Course: Laravel

Topic: Database & Migrations: Building Your Data Structure

Welcome, future Laravel artisan! πŸ§™β€β™‚οΈ Today, we're diving into the very foundation of most web applications: the database. We'll learn how to talk to our database, shape it to our will, and even create a whole bunch of fake users to make our app look popular from day one.


1. Configuring Database Connections (.env secrets) 🀫

The Problem: Your application needs to talk to a database. To do that, it needs credentials: a username, a password, a host, and the database name. Where do you store this sensitive information? You can't just slap it into a file and commit it to your git repository. That's like leaving your house keys under the doormat – a terrible idea.

The Solution: The .env file

Laravel uses a special file called .env to store environment-specific variables. Think of it as your application's secret diary. It's for all the sensitive stuff that shouldn't be shared with the public. This file is listed in your .gitignore file by default, so you won't accidentally commit your database password and become front-page news for the wrong reasons.

How it Works:

Laravel's database configuration lives in config/database.php. If you open that file, you'll see a bunch of database connections defined (MySQL, PostgreSQL, SQLite, etc.). Each connection's settings are pulled from the .env file using the env() helper function.

Let's Get Practical:

  1. Open your .env file: It's in the root directory of your Laravel project.

  2. Find the database section: It will look something like this:

    env
    DB_CONNECTION=mysql
    DB_HOST=127.0.0.1
    DB_PORT=3306
    DB_DATABASE=laravel
    DB_USERNAME=root
    DB_PASSWORD=
  3. Update the values: Change these to match your local database setup. For example, if you created a MySQL database named my_awesome_app with a user sail and password password, you'd change it to:

    env
    DB_CONNECTION=mysql
    DB_HOST=127.0.0.1
    DB_PORT=3306
    DB_DATABASE=my_awesome_app
    DB_USERNAME=sail
    DB_PASSWORD=password

That's it! Your Laravel application now knows how to connect to your database. ✨


2. Migrations: Version Control for Your Database πŸ•°οΈ

The Problem: Imagine you're working on a team. You add a new is_admin column to the users table. How do you tell your teammates to do the same? You could send a Slack message, but what if they miss it? What if you need to set up the project on a new computer? Manually keeping everyone's database schema in sync is a recipe for disaster.

The Solution: Migrations

Migrations are like version control for your database schema. They are PHP files that describe changes to your database, like creating tables, adding columns, or dropping them. This allows your team to easily modify and share the application's database schema.

Creating a Migration:

Let's create a migration to make a posts table. Open your terminal and run this Artisan command:

bash
php artisan make:migration create_posts_table

This will create a new file in your database/migrations directory. The filename will have a timestamp, which Laravel uses to run the migrations in order. Inside, you'll find a class with two methods: up() and down().

  • up(): This method runs when you migrate your database. It's where you define the changes you want to make.
  • down(): This method runs when you roll back a migration. It should reverse the changes made in the up() method.

Let's build our posts table:

Open the newly created migration file and edit the up() method:

php
public function up(): void
{
    Schema::create('posts', function (Blueprint $table) {
        $table->id(); // An auto-incrementing primary key
        $table->string('title');
        $table->text('body');
        $table->timestamps(); // created_at and updated_at columns
    });
}

And in the down() method, we'll tell Laravel how to undo this:

php
public function down(): void
{
    Schema::dropIfExists('posts');
}

Running Migrations:

To run all your outstanding migrations, just run this command:

bash
php artisan migrate

Your posts table will now exist in the database! πŸŽ‰


3. Modifying Existing Tables & Rolling Back Changes πŸ”™

The Problem: You've created your posts table, but now you realize you forgot to add a column for the author. You can't just edit the original migration file, because your teammates have already run it.

The Solution: A New Migration for Modifications

You can create a new migration to modify an existing table.

bash
php artisan make:migration add_author_to_posts_table --table=posts

Notice the --table=posts flag. This tells Laravel that we're modifying the posts table and pre-fills the migration file for us.

Now, let's add our user_id column in the new migration's up() method:

php
public function up(): void
{
    Schema::table('posts', function (Blueprint $table) {
        $table->foreignId('user_id')->constrained()->onDelete('cascade');
    });
}

And to reverse this in the down() method:

php
public function down(): void
{
    Schema::table('posts', function (Blueprint $table) {
        $table->dropForeign(['user_id']);
        $table->dropColumn('user_id');
    });
}

Run php artisan migrate again, and your posts table will now have a user_id column.

Rolling Back:

What if you made a mistake? You can roll back the last "batch" of migrations you ran with this command:

bash
php artisan migrate:rollback

This will execute the down() method of the migrations in the last batch. You can also roll back a specific number of steps:

bash
php artisan migrate:rollback --step=3 // Rolls back the last 3 migration batches

Fun Fact: Rolling back without a proper down() method is like trying to unscramble an egg. It's messy and you'll probably just make things worse. Always make sure your down() method properly reverses your up() method!


4. Seeding and Factories: Populating Fake Data for Development 🎭

The Problem: You're building a beautiful blog, but it looks a bit empty. You need some posts to see how your layout looks with actual data. Manually creating a bunch of posts is tedious and time-consuming.

The Solution: Seeders and Model Factories

  • Model Factories are like blueprints for your models. They define how to create fake instances of your models with realistic-looking data.
  • Seeders are classes that use these factories to populate your database with that fake data.

Creating a Factory:

First, let's create a factory for our Post model:

bash
php artisan make:factory PostFactory

This will create a PostFactory.php file in database/factories. Let's define what a fake post should look like:

php
namespace Database\Factories;

use Illuminate\Database\Eloquent\Factories\Factory;

class PostFactory extends Factory
{
    public function definition(): array
    {
        return [
            'title' => $this->faker->sentence(),
            'body' => $this->faker->paragraph(),
            // We'll handle user_id in the seeder
        ];
    }
}

Laravel factories use the popular Faker library to generate all sorts of random data.

Creating a Seeder:

Now, let's create a seeder to use our new factory:

bash
php artisan make:seeder PostSeeder

This creates a PostSeeder.php file in database/seeders. Here's how we'll use it to create 50 posts for our first user:

php
namespace Database\Seeders;

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

class PostSeeder extends Seeder
{
    public function run(): void
    {
        // Get the first user
        $user = User::first();

        // Create 50 posts for that user
        Post::factory()->count(50)->create([
            'user_id' => $user->id,
        ]);
    }
}

Running the Seeder:

Before we can run our PostSeeder, we need to tell Laravel about it. Open database/seeders/DatabaseSeeder.php and add this line to the run() method:

php
public function run(): void
{
    $this->call([
        PostSeeder::class,
    ]);
}

Now, you can seed your database with this command:

bash
php artisan db:seed

And just like that, you have a database full of fake posts! πŸš€

A common and very useful command is migrate:refresh --seed, which will roll back all of your migrations, re-run them, and then run all of your seeders. This is fantastic for quickly resetting your database during development.


Further Reading πŸ“š

Challenge

You are tasked with setting up the database structure and test data generation for a new 'reviews' feature in your application. Your goal is to write the PHP code for a migration's up() method and a model factory's definition() method.

Part 1: Migration

Write the body of the up() method to create a reviews table. The table must have the following columns and constraints:

  • An auto-incrementing big integer primary key named id.
  • A foreign key product_id that references the id on a products table. It should be constrained and cascade on delete.
  • A string column title with a maximum length of 200 characters.
  • A text column named content that can be null.
  • An unsigned tiny integer column named rating for a score from 1 to 5.
  • A string column reviewer_email which must be unique.
  • A boolean column is_approved which defaults to false.
  • The standard created_at and updated_at timestamp columns.

Part 2: Model Factory

Write the body of the definition() method for a ReviewFactory. This method should return an array defining the attributes for a fake review, using the Faker library.

  • product_id: Assume you will pass this in when creating the model, so it does not need to be defined here.
  • title: A sentence with exactly 6 words.
  • content: A paragraph with 3 sentences.
  • rating: A random number between 1 and 5 (inclusive).
  • reviewer_email: A unique, safe email address.
  • is_approved: A boolean value with a 75% chance of being true.

Expected result

Part 1: Migration Solution

The up() method should correctly define the reviews table schema using the Blueprint helper.

php
Schema::create('reviews', function (Blueprint $table) {
    $table->id();
    $table->foreignId('product_id')->constrained()->cascadeOnDelete();
    $table->string('title', 200);
    $table->text('content')->nullable();
    $table->unsignedTinyInteger('rating');
    $table->string('reviewer_email')->unique();
    $table->boolean('is_approved')->default(false);
    $table->timestamps();
});

Part 2: Factory Solution

The definition() method should return an array mapping model attributes to Faker generator methods.

php
public function definition(): array
{
    return [
        'title' => fake()->sentence(6),
        'content' => fake()->paragraph(3),
        'rating' => fake()->numberBetween(1, 5),
        'reviewer_email' => fake()->unique()->safeEmail(),
        'is_approved' => fake()->boolean(75),
    ];
}
php

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.