January 6, 2024 · 4 min read · 35 views
We're excited to announce that we have updated all of our blog post examples to reflect the new Laravel 11 version! Our previous examples were based on Laravel 10, but with the release of Laravel 11, we wanted to ensure that our readers have access to the most up-to-date information and examples.
Note: Make sure you've already run the commands on our previous post when we set the models of our application. The following information assumes you've already followed that article successfully.
After creating the database schema for our blog with Laravel migrations, it's time to populate our tables with sample data. When building an application in Laravel, it's important to have a rich dataset for testing and development. Laravel's Seeders and Factories work hand in hand to create this data. Factories define how default data for models should be generated, and Seeders use those factories to populate the database. Let's combine Seeders and Factories to fill our blog with dynamic, realistic data.
Seeders are PHP classes that feed data into our database tables. They help us:
Test Features: With seeders, we can create enough data to test our application.
Develop Consistently: Seeders ensure every developer on the team has a consistent set of data.
Demo Purposes: Seeders provide a full demo for clients without manually entering data.
Factories in Laravel are classes that define how to generate fake data for your models. They use the Faker library to create realistic data values. Let's modify the factories for our blog's Users, Profiles, Posts, Tags, and Images.
Note: If you followed the article where we set the models then you already have the following files below and are ready to code. Otherwise, you won't be able to find these files in your app.
<?php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
class UserFactory extends Factory
{
public function definition()
{
return [
'name' => fake()->name,
'email' => fake()->unique()->safeEmail,
'email_verified_at' => now(),
'password' => static::$password ??= Hash::make('password'), // password is password
'remember_token' => Str::random(10),
];
}
}
You can create a Profile factory, but in this example, we'll handle profile creation directly in the User Seeder to ensure each user has one profile.
<?php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
class PostFactory extends Factory
{
public function definition()
{
return [
'user_id' => User::inRandomOrder()->first()->id,
'title' => fake()->sentence,
'content' => fake()->paragraph,
];
}
}
Tags may not necessarily need a factory if you're using a predefined set of tags, but you can create one if you want dynamic tag names.
<?php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
class ImageFactory extends Factory
{
public function definition()
{
return [
'path' => fake()->imageUrl(),
];
}
}
Let's create seeders for our blog's users, profiles, posts, tags, and images to see how these seeds blossom into a rich database ready for development.
We'll start by creating a seeder for the users
table. Laravel uses the Faker
library to generate fake data that looks real.
<?php
use Illuminate\Database\Seeder;
use App\Models\User;
class UsersSeeder extends Seeder
{
public function run()
{
// Create 10 users and attach a profile to each
User::factory()->count(10)->create()->each(function ($user) {
$user->profile()->save(Profile::factory()->make());
});
}
}
Next, we'll seed profiles for each user. Since each user should only have one profile, we'll handle this within the User factory itself.
For the posts
table, we'll create a seeder that generates 50 blog posts for our users.
<?php
use Illuminate\Database\Seeder;
use App\Models\Post;
class PostsSeeder extends Seeder
{
public function run()
{
Post::factory()->count(50)->create();
}
}
Tags are the keywords for categorizing posts. We can seed a few common tags.
<?php
use Illuminate\Database\Seeder;
use App\Models\Tag;
class TagsSeeder extends Seeder
{
public function run()
{
$tags = ['Laravel', 'PHP', 'JavaScript', 'CSS', 'HTML'];
foreach ($tags as $tag) {
Tag::create(['name' => $tag]);
}
}
}
Finally, we'll seed some images for our posts. We'll assume each post has at least one image.
<?php
use Illuminate\Database\Seeder;
use App\Models\Image;
use App\Models\Post;
class ImagesSeeder extends Seeder
{
public function run()
{
// Assume each post needs at least one image
Post::all()->each(function ($post)
{
Image::factory()->create(
[
'imageable_id' => $post->id,
'imageable_type' => get_class($post),
]
);
});
}
}
To run all our seeders, we can call them from the DatabaseSeeder
class. This class is executed when you run the db:seed
Artisan command.
<?php
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
public function run()
{
$this->call([
UserSeeder::class,
PostSeeder::class,
TagSeeder::class,
ImageSeeder::class,
]);
}
}
With our seeders ready, we can fill our database with the sample data using the following command:
php artisan migrate:fresh --seed
NOTE: This will remove all previous data and start fresh.
By using Laravel seeders and factories to generate user profiles, blog posts, tags, and images, we can simulate a blog application. This data not only aids in development and testing but also provides a visual demo for presenting our project to others.
If you need help with a Laravel project let's get in touch.
Lucky Media is proud to be recognized as a Top Laravel Development Agency
Technologies:
Related Posts
Stay up to date
Be updated with all news, products and tips we share!