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:
Open your
.envfile: It's in the root directory of your Laravel project.Find the database section: It will look something like this:
envDB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=laravel DB_USERNAME=root DB_PASSWORD=Update the values: Change these to match your local database setup. For example, if you created a MySQL database named
my_awesome_appwith a usersailand passwordpassword, you'd change it to:envDB_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:
php artisan make:migration create_posts_tableThis 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 theup()method.
Let's build our posts table:
Open the newly created migration file and edit the up() method:
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:
public function down(): void
{
Schema::dropIfExists('posts');
}Running Migrations:
To run all your outstanding migrations, just run this command:
php artisan migrateYour 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.
php artisan make:migration add_author_to_posts_table --table=postsNotice 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:
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:
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:
php artisan migrate:rollbackThis will execute the down() method of the migrations in the last batch. You can also roll back a specific number of steps:
php artisan migrate:rollback --step=3 // Rolls back the last 3 migration batchesFun 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:
php artisan make:factory PostFactoryThis will create a PostFactory.php file in database/factories. Let's define what a fake post should look like:
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:
php artisan make:seeder PostSeederThis creates a PostSeeder.php file in database/seeders. Here's how we'll use it to create 50 posts for our first user:
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:
public function run(): void
{
$this->call([
PostSeeder::class,
]);
}Now, you can seed your database with this command:
php artisan db:seedAnd 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_idthat references theidon aproductstable. It should be constrained and cascade on delete. - A string column
titlewith a maximum length of 200 characters. - A
textcolumn namedcontentthat can be null. - An unsigned tiny integer column named
ratingfor a score from 1 to 5. - A string column
reviewer_emailwhich must be unique. - A boolean column
is_approvedwhich defaults tofalse. - The standard
created_atandupdated_attimestamp 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 beingtrue.
Expected result
Part 1: Migration Solution
The up() method should correctly define the reviews table schema using the Blueprint helper.
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.
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),
];
}