Laravel database seeding tutorial with example

Laravel seeder is used to insert dummy data to the table for the testing purposes called database seeding. By default, Laravel ships with a database seeder package called fzaninotto/faker. You can find all the default package that ships with Laravel in the componser.json file. All seeds classes are stored in database/seeds directory.

Let's get started

# Installing Laravel

To use Laravel seeder with an example we will install the fresh project for this tutorial. We will be using the relationship between tables to insert the fake / dummy data.

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

Once you are done with the installation. Open the Larave fresh installed project in your favorite code editor.

# Configure MySql database

Next, Open your .env file and add your database configuration.

# .env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_seeders
DB_USERNAME=root
DB_PASSWORD=root

Here, My database name is laravel_seeders, and the username & password is root.

# Creating Migration File

Once we are done with the database configuration create the migration file. We will create two tables in this tutorial user and post table and set up the relationship. By default, the user model and migration are already shipped with Laravel. So we need to create only post migrations and model

Enter the following command to create the migrations for Post table in the Database.

php artisan make:model Post -m

The above command will generate the post's model and migration file. Now let's add the fields in the post migration file.

# database/migrations/2019_12_28_113609_create_posts_table.php

public function up()
{
    Schema::create('posts', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->integer('user_id');
        $table->string('title');
        $table->longText('description');
        $table->timestamps();
    });
}

 

In the above code add the required fields for the Post table.

# Setting up Relationships

Once you are done with the migrations. Let's create the relationship between the User and the Post model. Copy and paste the following command in the Post model.

# App/Post.php

public function User()
{
	return $this->belongsTo('User');
}

 And Copy and paste the following code in the User model.

# App/User.php

public function posts()
{
    return $this->hasMany('Post');
}

In the above code, a user can have more than one post and a post belongs to only one user.

 

# Creating database seeders file

Once You are done with setting up the relationship between both tables. Enter the following command to create the seeder for both tables.

php artisan make:seeder UsersTableSeeder
php artisan make:seeder PostsTableSeeder

Now that you have created the seeder file for both tables. Let's create a factory file for each table.

# Creating factory file

The factory file is used to define the types of fake data that need to be inserted into the table. By default, the UserFactory class is already shipped with Laravel. So we have to create only a post factory class. Enter the following command to generate the factory file.

php artisan make:factory PostFactory

The above command will create PostFactory class under database/factories directory. Open and paste the following code

# database/factories/PostFactory.php

<?php

/** @var \Illuminate\Database\Eloquent\Factory $factory */

use App\Post;
use Faker\Generator as Faker;

$factory->define(Post::class, function (Faker $faker) {
	return [
	    'name' => $faker->sentence(6),
	    'user_id' => factory('App\User')->create()->id,
	    'description' => $faker->text()
	];
});

In the above code, we have defined a factory and passing App\Post::class model as first parameter and a callback function as the second parameter where we have injected faker class for generating the fake data. we are returning key as the columns name and the value as the faker data for the post table.

  • $faker->sentence will generate a sentence of 6 words as we have passed 6 as an argument.
  • facotry('App\User')->create()->id will create a user and attach it to each post.
  • $faker->text() will generate paragraph

Now we have created and set up the factories class. Let's update the tables seeder class that we created earlier.

Add the below code in the PostsTableSeeder file

# database/seeds/PostsTableSeeder.php

public function run()
{
    factory('App\Post', 15)->create();
}

The above code will create 15 posts in the database as well as 10 users as we have defined user_id as User factory that will create user and attach its id to each created post.

 

Same thing we will do for user table. Let's update the UserTableSeeder.php 

public function run()
{
    factory('App\User', 15)->create();
}

The above code will create 15 users in the database.

Now let's update the DatabaseSeeder.php file which can be located under database/seeds/DatabaseSeeder.php. Copy and paste the following code

public function run()
{
    // Disable all mass assignment restrictions
    Model::unguard();
 
    $this->call(PostsTableSeeder::class);
 
    // Re enable all mass assignment restrictions
    Model::reguard();
}

# Seeding the database

Now that we have setup up everything. Run the following command to migrate the table first.

php artisan migrate

The above command will create the table as we created the migrations file above. Now enter the below command to seed the database.

php artisan db:seed