How To Generate and Use Fake Records with Laravel Model Factories

Laravel Model Factories are a great tool for quickly generating fake records for testing and development purposes. They allow you to quickly create a large number of records with random data, which can be used to test your application or to populate a development database. In this tutorial, we’ll show you how to generate and use fake records with Laravel Model Factories.

1. Create a Model Factory

The first step is to create a Model Factory. This is a class that defines the structure of the records you want to generate. To create a Model Factory, you need to create a new file in the database/factories directory. The file should be named after the model you want to generate records for, and it should contain a class with the same name.

For example, if you want to generate fake records for a User model, you would create a file called UserFactory.php in the database/factories directory, and it would contain a class called UserFactory.

2. Define the Structure of the Records

Once you’ve created the Model Factory, you need to define the structure of the records you want to generate. This is done using the define() method. The define() method takes two arguments: the model you want to generate records for, and a closure that defines the structure of the records.

For example, if you want to generate fake records for a User model, you could define the structure of the records like this:

UserFactory::define(User::class, function (Faker $faker) { return [ ‘name’ => $faker->name, ’email’ => $faker->unique()->safeEmail, ‘password’ => bcrypt(‘password’), ]; });

In this example, we’re using the Faker library to generate random data for the name and email fields. We’re also setting the password field to a fixed value of “password”.

3. Generate Fake Records

Once you’ve defined the structure of the records, you can generate fake records using the factory() method. The factory() method takes two arguments: the model you want to generate records for, and the number of records you want to generate.

For example, if you want to generate 10 fake records for a User model, you could do it like this:

$users = factory(User::class, 10)->create();

This will generate 10 fake records and save them to the database.

4. Use the Fake Records

Once you’ve generated the fake records, you can use them in your tests or development environment. For example, if you want to test a feature that requires a logged-in user, you can use one of the fake records you generated.

Conclusion

In this tutorial, we’ve shown you how to generate and use fake records with Laravel Model Factories. Model Factories are a great tool for quickly generating fake records for testing and development purposes. We hope you’ve found this tutorial helpful.

Testing is essential to web development. Laravel Model factories define database records in a predictable and easily replicable way so that your app tests are consistent and controlled. Model factories define a set of default attributes for each of your Eloquent models.

For example, if you’re making a blogging app allowing authors and moderators to approve comments before they go live, you’d need to test if the function works properly before deploying it to your users. All this requires test data.

To test the blogging app described above, you need comments data to imitate and test your application’s functionality. Laravel allows you to do that without getting comments from actual users by using Laravel factories and Faker to generate fake data.

This article explains how to get comments data without comments from real users.

Prerequisites

To complete this tutorial, you must be familiar with the following:

XAMPP is a free and easy-to-install Apache distribution that contains PHP, Perl, and MariaDB — a MySQL database. This tutorial uses the latest version, 8.1.10, which installs PHP 8.1.10. Read this article if installing XAMPP for MacOS or this guide for Linux. This tutorial uses XAMPP on Windows.

Composer is a tool that allows you to define, install and download the packages your web app depends on in development and production. This tutorial uses version v2.4.4 of Composer, which requires PHP version 7.2+. You use Composer to install the Laravel installer for this tutorial.

You can also download the complete code for the project to follow along.

How To Set Up the Project

In this section, you’ll create a Laravel project and connect it to a database. Let’s take a look at all that entails and how to accomplish it.

Install Laravel Installer

To create a Laravel project quickly, install the Laravel installer:

composer global require laravel/installer

This code installs the Laravel installer globally on your machine.

Create a Laravel Project

Next, create a Laravel project by running the following:

laravel new app-name

This code bootstraps a new Laravel project and installs all the dependencies:

Creating the Laravel project
Creating the Laravel project

Another easier way to install Laravel is to use Composer directly.

composer create-project laravel/laravel app-name

You don’t need to install the Laravel installer when using the method above.

Start the App

You can now change the directory to app-name and start the project using Laravel’s own command-line interface (CLI) tool, Artisan:

php artisan serve

This code begins the project and connects it to localhost:8000 or any other available port if port 8000 is in use. On localhost:8000, you should see something like this:

The Laravel website homepage
Laravel

Create a Database

To connect your app to a database, you must create a new database using XAMPP’s PHPMyAdmin graphical user interface. Go to localhost/phpmyadmin and click New on the sidebar:

The Create Database form in PHPMyAdmin
Create database form

The image above shows the Create Database form with app_name as the database name.

Click Create to create a database.

Edit the .env File

To connect your app to a database, you must edit the DB part of the .env file:

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

This code fills the database credentials with your database name, username, port, password, and host. You’re now ready to start creating factories and models.

Note: Replace the values with your database credentials. Also, if you encounter the “Access denied for user,” error, put the values for DB_USERNAME and DB_PASSWORD in double-quotes.

How To Generate Fake Data

After creating the app and connecting it to the database, you can now create the necessary files to generate fake data in the database.

Create the Comment Model

Create the model file to interact with the database tables. To create a model, use Artisan:

php artisan make:model Comment

This code creates a Comment.php file inside the app/Models folder with some boilerplate code. Add the following code below the use HasFactory; line:

 protected $fillable = [
      'name',
      'email',
      'body',
      'approved',
      'likes'
    ];

This code lists the fields you want to allow mass assignments because Laravel protects your database from mass assignments by default. The Comment model file should now look like this:

The Comment model file
Comment model file

Create the Migration File

After creating the model file and declaring the $fillable array, you must create the migration file using the command below:

php artisan make:migration create_comments_table

Note: The naming convention for creating migrations in Laravel is usually snake_case, also known as underscore_case. The first word is the action, the second word is a plural of the model, and the last word is the feature that gets created inside the project. This means you’ll write create_books_table when creating a migration for a Book model.

This code creates a file named yyyy_mm_dd_hhmmss_create_comments_table inside the database/migrations folder.

Next, edit the up function inside yyyy_mm_dd_hhmmss_create_comments_table:

public function up()
    {
  Schema::create('comments', function (Blueprint $table) {
    $table->id();
    $table->string('name');
    $table->string('email');
    $table->longText('body');
    $table->boolean('approved');
    $table->integer('likes')->default(0);
    $table->timestamps();
    });
    }

This code creates a schema that creates a table with the columns: id, name, email, body, approved, likes, and timestamps.

Run the Migrations

Creating and editing the migrations file won’t do anything until you run them using the command line. If you look at the database manager, it’s still empty.

Run the migrations using Artisan:

php artisan migrate

This command runs all the migrations inside database/migrations because it’s the first migration since creating the app:

Successful migrations
Successful migrations

The following image shows all the migration files that you ran. Each represents a table in the database:

The Database after migrations
Database after migrations

Create the CommentFactory File

Create a factory file that contains your definition function. For this demonstration, you’ll create a factory using Artisan:

php artisan make:factory CommentFactory.php

This code creates a CommentFactory.php file inside the database/factories folder.

The Definition Function

The function inside CommentFactory defines how Faker generates fake data. Edit it to look like this:

public function definition()
  {
   return [
     'name' => $this->faker->name(),
     'email' => $this->faker->email(),
     'body' => $this->faker->sentence(45),
     'approved' => $this->faker->boolean(),
     'likes' => $this->faker->randomNumber(5)
     ];
    }

This code tells Faker to generate the following:

  • A name
  • An email address
  • A paragraph that contains 45 sentences
  • An approved value that can only be true or false
  • A random number between 0 and 9999

Connect the Comment Model To CommentFactory

Link the Comment model to CommentFactory by declaring a protected $model variable above the definition:

protected $model = Comment::class;

Also, add the use App\Models\Comment; to the file dependencies. The CommentFactory file should now look like this:

The CommentFactory file
The CommentFactory file

How To Seed the Database

Seeding in programming means generating random fake data for a database for testing purposes.

Now that you’ve created the model, run migrations, and created the definition inside CommentFactory, run the seeder using the DatabaseSeeder file.

Create the CommentSeeder File

Create a seeder file that uses factory to generate the data:

php artisan make:seeder CommentSeeder.php

This code creates a CommentSeeder.php file inside the database/seeders folder.

Edit the Run Function

Connect the Comment model to the CommentSeeder. Add the following code inside the run function:

Comment::factory()->count(50)->create();

This code tells the CommentSeeder to use the Comment model and CommentFactory’s definition function to generate 50 comments inside the database. Also, add the use App\Models\Comment; to the file dependencies. The CommentSeeder file should now look like this:

The CommentSeeder file
CommentSeeder file

Note: You can configure Faker to create local data. For example, you can set it to generate Italian names instead of random names by setting faker_locale inside the app/config.php file to it_IT. You can read more about Faker Locales in this guide.

Run the Seeder

Next, run the seeder file with Artisan:

php artisan db:seed --class=CommentSeeder

This code runs the seeder file and generates 50 rows of fake data in the database.

Database seed successful
Database seed successful

The database should now have 50 rows of fake data that you can use to test your application’s functions:

50 rows of data in the database
50 rows of data in the database

How To Reset the Database

When using the generated data for testing, reset the database each time you run a test. Suppose you wanted to test the approved comment toggle feature. Refresh the database after each test to ensure the previously generated data won’t interfere with future tests.

Use RefreshDatabase

Refresh the database using the RefreshDatabase trait inside the test file.

Navigate to ExampleTest.php inside the tests/Feature folder to the comment use Illuminate\Foundation\Testing\RefreshDatabase; and add the following line of code above the test_the_application_returns_a_successful_response  function:

use RefreshDatabase;

The ExampleTest.php file should now look like this:

The ExampleTest file
ExampleTest file

Run the Test

After adding the RefreshDatabase trait to the test file, run the test using Artisan:

php artisan test

This code runs all the tests in the app and refreshes the database after the tests, as shown in the image below:

A successful Artisan test
A successful Artisan test

Now, check the database to see the empty comments table:

An empty comments database
Empty comments database

Summary

This article covered how to create a Laravel project, connect it to a database, and create and configure models, migration, factory, and seeder files to generate random data for the database. It also discussed how to reset the database after running tests.

You’ve now seen how Laravel Factories and Faker make it easy to generate any amount of test data in minutes to test an application or even as a placeholder — with minimal configuration.

When your Laravel app is ready to deploy, you can do it on Kinsta’s Application Hosting services quickly and efficiently.


Get all your applications, databases and WordPress sites online and under one roof. Our feature-packed, high-performance cloud platform includes:

  • Easy setup and management in the MyKinsta dashboard
  • 24/7 expert support
  • The best Google Cloud Platform hardware and network, powered by Kubernetes for maximum scalability
  • An enterprise-level Cloudflare integration for speed and security
  • Global audience reach with up to 35 data centers and 275 PoPs worldwide

Get started with a free trial of our Application Hosting or Database Hosting. Explore our plans or talk to sales to find your best fit.





Source link

Jaspreet Singh Ghuman

Jaspreet Singh Ghuman

Jassweb.com/

Passionate Professional Blogger, Freelancer, WordPress Enthusiast, Digital Marketer, Web Developer, Server Operator, Networking Expert. Empowering online presence with diverse skills.

jassweb logo

Jassweb always keeps its services up-to-date with the latest trends in the market, providing its customers all over the world with high-end and easily extensible internet, intranet, and extranet products.

Contact
San Vito Al Tagliamento 33078
Pordenone Italy
Item added to cart.
0 items - 0.00
Open chat
Scan the code
Hello 👋
Can we help you?