CodeBriefly
Tech Magazine

Basic Use of Model Factories in Laravel

2 4,123

Get real time updates directly on you device, subscribe now.

In this article, we will discuss the basic use of Model Factories in Laravel. Laravel comes with the feature called model factories that are offered to made fake models quickly. It’s used in the database testing and database seeding. Let’s start the discussion on this feature by building out the beginning of a little functional web app.

We can use the user’s table for the authors and create a new post table. I’m assuming this you are familiar with the basic Laravel installation, authentications. Because we need a working Laravel app to make this tutorial complete. If you are not familiar then please have a look at given tutorials.

Next, back to the current tutorial and create posts modal and migration from the PHP artisan console command. You can create both in one command by using the “-m” or “–migration” flag with the “make:model command.

php artisan make:model Posts -m

After executing the above command, our model and migration file is ready for use. Posts Model is located at app directory and the migration file is located at database/migrations directory. Let’s define the posts relationship in the User Model located at app/User.php. Here’s no need to create the User Model because Laravel comes with default User Model.

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

# Update Migration

Now, time to update the posts migration. Open the migration file which we create when creating our Posts Model and update with the given code.

public function up()
{
  Schema::create('posts', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('user_id');
    $table->string('post_title');
    $table->text('post_content');
    $table->timestamps();
  });
}

In the above migration, we are just adding a user_id relationship to the user’s table, post_title and post_content. Run the migration now:

php artisan migrate

This command creates all the tables which are necessary for our apps such as user, password_resets, and posts. All those tables created in the linked database which one we add in the .env file.

# Building Database Seeds

In Laravel provides a feature called database seeder. It is used for inserting fake data into the database.

Let’s create a seeder for users and posts table.

// User table seeder
php artisan make:seeder UserTableSeeder

// PostsTableSeeder
php artisan make:seeder PostsTableSeeder

Now time to update the database/seeds/DatabaseSeeder.php file and adjust the run method to the following:

public function run()
{
  $this->call(UserTableSeeder::class);
  $this->call(PostsTableSeeder::class);
}

Now, these seed classes are ready and they need instructions on what to insert.

# Creating Model Factories

Model Factories can use them to build out “fake” models which can be used for both seed data and in testing. Laravel comes with UserFactory.php, you can check this file for the overview.

use Faker\Generator as Faker;

$factory->define(App\User::class, function (Faker $faker) {
  return [
    'name' => $faker->name,
    'email' => $faker->unique()->safeEmail,
    'password' => '$2y$10$TKh8H1.PfQx37YgCzwiKb.KjNyWgaHb9cbcoQgdIVFlYg7B77UdFm', // secret
    'remember_token' => str_random(10),
  ];
});

To explain the above code, “App\User::class model as the first parameter and then a callback function. Which defines the data that goes in the columns. Faker which is a PHP library that generates fake data. Faker is powerful and can be used for a number of different field types.

Now, let’s create a new model factory for our Posts model. Here is the code:

use Faker\Generator as Faker;

$factory->define(App\Posts::class, function (Faker $faker) {
  return [
    'user_id' => function () {
      return factory(App\User::class)->create()->id;
    },
    'post_title' => $faker->sentence(5),
    'post_content' => $faker->text()
  ];
});

With this, we generate a post title with five words, and finally some dummy text for the post content.

Now switch back to our seed classes and use these factories to generate the data.

Open the UserTableSeeder and update the run method:

The factory(App\User::class, 5)->create(), build a User class and we want 5 users then create them and saving in the database.

Now, time seed the database.

php artisan db:seed

Everything ready now, after executing the db:seed command. Our posts and users with fake data generated.

model factories

In this article, we are discussing Modal Factories. In future, we will discuss more on Laravel Model Factories such as the use of model factories in testing. Feel free to add comments if any query.

If you like our content, please consider buying us a coffee.
Thank you for your support!
Buy Me a Coffee

Get real time updates directly on you device, subscribe now.

2 Comments
  1. Ned Berry says

    Thanks for this article, It will saved lot of my time 🙂

    1. Code Briefly says

      Thanks Ned 🙂

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. AcceptRead More