How to seed test data into a database in Laravel?

Laravel comes with in-built support to seed test data into a database. There are a few steps you should follow to successfully insert test data into the database. In this article, I will demonstrate to you how to accomplish it.

Before we begin, let's first install composer and nodejs.

Let’s start with a new Laravel project. To create a new Laravel project run

composer create-project --prefer-dist laravel/laravel blog

or

laravel new blog

Then create a database and go into your .env file and input your database name, the database user name, and the database password.

DB_DATABASE=blog_db
DB_USERNAME=root
DB_PASSWORD=secret

The next step would be to create a migration. To generate migration run

Migrations are typically paired with Laravel’s schema builder to build your application’s database schema.

php artisan make:migration create_posts_table

This will create a migration for the Posts table in database\migrations directory

public function up(){
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('title');
$table->text('content');
$table->json('meta_data')->nullable();
$table->bigInteger('author_id');
$table->bigInteger('category_id');
$table->timestamps();
});
}

The next step would be to create a model. To generate a model run

Each database table has a corresponding “Model” which is used to interact with that table. Models allow you to query for data in your tables, as well as insert new records into the table.

php artisan make:model Post

This will create a model Post in app\Models directory

class Post extends Model
{
use HasFactory;
protected $fillable = [
'title',
'content',
'post_type',
'meta_data',
'category_id',
'author_id',
];
}

The next step, to insert records into your database create a factory

When testing, you may need to insert a few records into your database before executing your test. Instead of manually specifying the value of each column when you create this test data, Laravel allows you to define a default set of attributes for each of your Eloquent models using model factories.

As of now, Laravel uses the Faker package to generate fake test data for you. Sadly this package is archived, which means from PHP 8 onwards it will not work. Read here to know more about why this package was discontinued.

Update: After the fzaninotto/Faker package is archived Laravel now uses FakerPHP/Faker forked from fzaninotto/Faker.

php artisan make:factory PostFactory --model=Post

This will create a factory name PostFactory in database\factories directory

class PostFactory extends Factory
{
protected $model = Post::class;
public function definition()
{
return [
'title' => $this->faker->sentence,
'content' => $this->faker->paragraph,
'author_id' => $this->faker->numberBetween(1, 100),
'category_id' => $this->faker->numberBetween(1, 10),
];
}
}

The final step is to add the above-created factory in the database seeder, which creates the data when you run database:seed command.

Laravel includes a simple method of seeding your database with test data using seed classes. By default, a DatabaseSeeder class is defined for you.

class DatabaseSeeder extends Seeder
{
public function run()
{
\App\Models\User::factory(100)->create();
\App\Models\Post::factory(1500)->create();
}
}

Now run php artisan migrate:fresh --seed at your will to seed the database with test data.

The source code is available at https://github.com/mdutt247/laravel-news for you to refer to.

To dig deeper please check Laravel Documentation.

Read the next part, Creating Relationships of this tutorial.

Connect: Twitter, GitHub, Linkedin, MDITech

You can support by buying a coffee ☕️ here https://www.buymeacoffee.com/mdutt

--

--

--

Software Developer @ mditech.net

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Jumping into the world of Virtual Reality — with no background in coding.

HOW TO INSTALL WORDPRESS

Adventures in hardware: Part 2 — stumbling along

Best VPS Hosting Plans

4 Reasons Your Jenkins Pipelines Are Brittle

Parallel Thinking And Software Development

GraphQL and Go with AppSync and Lambda

JoSend: sending crypto as easy as sending messages

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Madhavendra Dutt

Madhavendra Dutt

Software Developer @ mditech.net

More from Medium

Learn Lumen Framework

Why (and how) you should use Message Queues in Magento 2

How to run feature tests in Laravel 9 in memory using SQLite

How to Clone Laravel Project from Git Repository and Run it on Local Machine