How can you make and use fake records using the Model Factories in Laravel - (r)

May 6, 2023
Generating and using fake records with Laravel model factories

Please share the news with

In the event of creating an online blog platform that allows authors and moderators to read comments before going live You'll need to verify the functionality before deploying it to customers. The test needs details.

This article explains how to obtain data on comments, without real user comments.

The requirements

For you to finish this course, it's vital to master these concepts:

  • XAMPP
  • Composer

Download the complete code for the project, so you are able to adhere to the steps of the project.

How Do I Set-Up the Project

In this part, you'll build the Laravel project, and then join it with the internet-based database. In this part, we'll discuss how to do it and what methods to achieve this.

Install Laravel Installer

To build your Laravel project quickly, you must install Laravel's installer. Laravel installer.

composer global require laravel/installer

This will install this Laravel installation on a global basis. device.

Create the Laravel Project

laravel new app-name

The code bootstraps a brand fresh Laravel project, and then installs every dependency:

Creating the Laravel project
The process involved in creating the Laravel project

A simpler method of installing Laravel is to avail of Composer directly.

composer create-project laravel/laravel app-name

It's not required to download Laravel installer. Installer for Laravel is available by following the instructions above.

Launch the application

Ability to alter the directory's application name and then start the project with Laravel's Command-Line Interface (CLI) tool, Artisan:

php artisan serve

The code starts the project with a connection to localhost:8000 or any other port available, once port 8000 is used. When you connect to localhost:8000, you'll see the following information:

The Laravel website homepage
Laravel

Design a Database

To connect your app to an existing database, you have to create a database with an XAMPP PHPMyAdmin GUI. Go to http://localhost/phpmyadmin and select New on the sidebar:

The Create Database form in PHPMyAdmin
Create database form

This photo shows how to fill out this form. Create Database form which uses the App_name as the name for the database.

Hit "Create" to create a database for your account.

Modify the .env Edit the.env file

In order to connect your app to your database, you'll have modify the DB section in your .env file:

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

The program will populate the database's data using the database's name username port, password and host. You're now ready to start creating factories and models.

Notice: Replace the values with the login credentials you have for your database. If you encounter the "Access not granted to the user" error, be sure to add the information to the DB_USERNAME and the DB_PASSWORD by using double quotation marks.

How to Generate Fake Data

After you've created your app, connecting it to your database, the app will be able to create file to create false database data.

Make the Comment Model

The model file is created for interaction with databases tables. To create a model, use Artisan:

php artisan make:model Comment

This code creates the Comment.php file inside the application/M orels folder. The file contains boilerplate code. This code must be added after that HaveFactory line:

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

Below is a listing of fields you'd prefer to be able to take huge assignments due to the fact that Laravel protects your database from large assignments automatically. The Comment model file is now expected to be displayed as:

The Comment model file
Comment model file

Make the Migration File

After you've created your model file, after declaring the $fillable array, you'll need to construct the migration files in the following manner:

php artisan make:migration create_comments_table

Notice: The naming convention used to build the migrations in Laravel generally known as the snake_case that is called underscore_case. The first word is a reference to the procedure, while the second is the plural of the model. The final word refers to the functionality that is created inside the program. That's why you enter create_books_table during the process of making a move for the 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(); ); 

The code generates the schema which will accommodate the columns to be named, email body, approval along with timestamps and likes.

The Migrations Run

Editing and creating the documents for the migration process won't do anything unless you run them using on the command line. When you visit the Database Manager, you'll find that the database manager is empty.

Do the migrations using Artisan.

php artisan migrate

This command runs every update in the database/migrations since it's the first time a migration is running since the program was launched:

Successful migrations
Successful migrations

Below, you'll be able to view every single migration file you have executed. Each file is one of the tables in your database:

The Database after migrations
Database after migrations

Create the CommentFactory File

Create a factory using the definition function. In this class, you'll construct a factory using the following tools:

php artisan make:factory CommentFactory.php

The code generates CommentFactory.php files. CommentFactory .php file within the directory databases/factories directory.

Defines the Function and Definitions

The process that is described by CommentFactory CommentFactory illustrates the method by the way that Faker creates False information. Modify it so that it appears 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) ]; 

The code instructs Faker to create this:

  • The title
  • An email address
  • The paragraph contains 45 phrases
  • A valid value which is only valid when the value is real or not.
  • Random numbers, which range between zero to 9999.

Comment Model can be connected to the Comment Model can be connected to Comment Model and then Comment Model to CommentFactory

Connect to the Comment model to the CommentFactory by declaring a protected $model variable in the context of:

protected $model = Comment::class;

In addition, it is recommended to include ModelsComment, an app that you have installed on your file's dependencies. Your CommentFactory file will now appear like: CommentFactory's File should look similar to:

The CommentFactory file
The CommentFactory File

Steps to Start Seeding the Database

In programming, it is an act that generates random data, which is then stored in databases for test reasons.

Once you've built your model, you are able to test it using changes and then include the definition inside CommentFactory. It is possible to run the database seeder with it's DatabaseSeeder file.

Make the CommentSeeder File

Create an seeker file that uses factory information to create it:

php artisan make:seeder CommentSeeder.php

The code produces commentseeder.php, which corresponds to what is the CommentSeeder .php file in the database/seeders directory.

Change the function run so it is able to modify

Join the comment model to the commentSeeder. Incorporate the following code into your running program:

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

The code instructs the CommentSeeder to use the Comment model, as well as the definition function of the CommentFactory to create 50 comments in the database. Incorporate appmodelsComment AppmodelsComment to the list of dependencies of the file. CommentsSeeder's file will now appear as follows: CommentSeeder file will now appear like this:

The CommentSeeder file
CommentSeeder file

Note: You can configure Faker to produce local information. You can, for instance set it up to generate Italian names, rather than random ones, by changing its faker_locale within the app/config.php file to it_IT. For further information, learn about Faker Locales on this instructional video.

Start the Seeder

Then you'll have the ability to start the program to make an ad-hoc Seeder application with Artisan:

php artisan db:seed --class=CommentSeeder

The program is executed on the Seeder file and produces 50 rows of fake information in the database.

Database seed successful
It is good to seed the database. excellent

The database now contains 50 rows of false information which you could use to check the functions of the program you are using:

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

Reseting the Database

If you're using created information for testing it is possible to modify the database every whenever you test. Imagine you want to try the option of removing the comments you approve. Revamp the database every test to ensure the data that was generated previously isn't creating problems in the next tests.

Utilize RefreshDatabase

Create a refreshed database by with the RefreshDatabase feature in 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:

Utilize RefreshDatabase

The ExampleTest.php file should seem to have a similar look to:

The ExampleTest file
The ExampleTest test document

Take the test

Once you have added to the RefreshDatabase feature to your test file, execute the test with Artisan:

php artisan test

This code performs every test within the application as well as update databases following each of the tests are completed. This can be shown in the next image:

A successful Artisan test
A successful Artisan test

Now, check your database to see if there is a comment database that's empty:

An empty comments database
Empty comments database

Summary

We've seen that Laravel Factories and Faker make it possible to produce the whole amount of test data quickly to evaluate an application, or even as placeholder data, with just a little setting up.

  • It is easy to set up and manage My dashboard. My dashboard
  • 24 hour expert assistance
  • The best Google Cloud Platform hardware and network powered by Kubernetes to provide the highest performance and scalability
  • A high-end Cloudflare integration that speeds up the process, and improve security
  • Aiming to reach a worldwide audience through as many as 35 data centers, and more than 275 PoPs around the globe

The post first appeared on here

This post was first seen on here