[Laravel 11] Create Dummy Table and Its Content using DB Seeder

Creating dummy data in your Laravel project is essential when building and testing applications. In this tutorial, we’ll walk through how to create a table and populate it with fake data using Laravel’s powerful Factory and Seeder features.

Step 1: Set Up Your Database

Before we begin, you need to set up your database and configure your Laravel project to connect to it. Open your .env file and update the following values based on your database credentials:

Once your database information is correctly entered, run the following command to initialize the database migrations,

This command will create all the necessary tables defined in your migrations folder, preparing the structure for the application data.

Step 2: Create a New Migration for the Posts Table

Now that your database is ready, let’s create a migration file for the posts table. This table will hold our sample data.

Open the generated migration file in database/migrations and define the columns for the posts table. Here’s an example of a basic structure:

Step 3: Create a Model for the Posts Table

After defining the table, it’s time to create a model that represents this table in your code. Run the following command to generate a model for Post:

Open the Post.php file in the app/Models directory and add the HasFactory trait to allow factory usage:

Step 4: Create a Factory to Generate Fake Data

Laravel factories are an easy way to create dummy data. Let’s create a factory for the Post model:

Open the newly created PostFactory.php in the database/factories directory. Customize it to generate random titles and content for your posts:

In this code, we use Laravel’s faker library to generate random titles and paragraphs, which will populate our posts table.

Step 5: Set Up a Seeder for the Posts Table

Seeders allow you to populate the database with default data. To create a seeder for the posts table, use the following command:

Edit the PostsTableSeeder.php file in database/seeders to utilize the factory we just created:

This seeder will generate 10 posts using the PostFactory. Feel free to change the count to create more or fewer posts as needed.

Step 6: Run the Seeder

Finally, it’s time to seed the database. Run the following command to execute the PostsTableSeeder:

If everything is set up correctly, you should see 10 new records in your posts table. Open your database viewer or run a query to verify the data.

You’ve successfully created a dummy posts table and populated it with fake data using Laravel factories and seeders! This setup is invaluable for testing and developing new features without requiring real data. By automating data creation, you can focus on building and improving the core functionality of your application.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.