Laravel Model Factories Tutorial With Example - Laravel 5.8 Seeding

Laravel Model Factories Tutorial With Example - Laravel 5.8 Seeding

Laravel Model Factories Tutorial With Example | Laravel 5.8 Seeding is today’s topic. Generating fake data manually for each model seed is cumbersome. Instead, you can use model factories to generate large amounts of database records conveniently.

Laravel has feature called model factories that allows us to generate fake data. It is beneficial for testing and seeding fake data into the database to see the code in action before any real-time user data comes in your application. Let’s deep dive into the Model Factories in Laravel.

PHP with Laravel for beginners – Become a Master in Laravel

Laravel Model Factories Tutorial

Faker is the PHP library that generates fake data for you. Whether you need to bootstrap your database, fill-in your persistence to stress test it or anonymize data taken from the production service, Faker is for you. You can find the faker documentation here.

By default, Laravel installs the faker library as a dependency. But you can also use the faker library to stand alone with any PHP project. You can install it using the following command. Remember, you do not need to install it with Laravel because by default it ships with Laravel.

composer require fzaninotto/faker

Okay, now back to the Laravel. Right now, Laravel 5.8 is the latest version. So install laravel.

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

Now, set the database credentials inside the .env file.

Next, create an Internet model and migration file by the following command.

php artisan make:model Internet -m

Switch to the createinternetstable.php file and add the following schema.

// create_internets_table.php

public function up() { Schema::create('internets', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('safeEmail'); $table->string('domainName'); $table->string('url'); $table->string('ipv6'); $table->timestamps(); }); }

Now, migrate using the following command.

php artisan migrate

Also, create an InternetFactory by using the following command.

php artisan make:factory InternetFactory

It will create an InternetFactory.php file inside the database >> factories >> InternetFactory.php file.

<?php

// InternetFactory.php

use Faker\Generator as Faker;

$factory->define(Model::class, function (Faker $faker) { return [ // ]; });

Right now, the above file is in the default state, but we need to add some attribute. Write the following code inside the InternetFactory.php file.

<?php

// InternetFactory.php

use Faker\Generator as Faker; use App\Internet;

$factory->define(Internet::class, function (Faker $faker) { return [ 'safeEmail' => $faker->safeEmail, 'domainName' => $faker->domainName, 'url' => $faker->url, 'ipv6' => $faker->ipv6 ]; });

The $faker->safeEmail will create fake safeEmail.

The $faker->domainName will create a fake domain name.

The $faker->url will create a fake URL.

The $faker->ipv6 will create a fake IPV6 address.

These are some attributes provided by the faker library. So, it will help us to create a different type of fake data. You can find more on this url.

In the above code, we have defined a factory for Internet.php model and passing it as a first parameter. Then we have the callback function that defines the data and returns it in an array.

Laravel Database Seeding

Next step is to create a table seeder. So type the following command to generate a table seeder for internets table.

php artisan make:seeder InternetsTableSeeder

Now, inside that file, we will write the code that will generate the fake records inside the database.

The file will be created inside the database >> seeds >> InternetsTableSeeder.php file.

Write the following code inside that file.

<?php

// InternetsTableSeeder.php

use Illuminate\Database\Seeder; use App\Internet;

class InternetsTableSeeder extends Seeder { /** * Run the database seeds. * * @return void */ public function run() { $count = 100; factory(Internet::class, $count)->create(); } }

When the above file runs, it will create 100 fake records in the database.

Okay, now it’s time to run the Seeder file. So write the following code inside the DatabaseSeeder.php file which is inside the database >> seeds folder.

<?php

// DatabaseSeeder.php

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder { /** * Seed the application's database. * * @return void */ public function run() { $this->call(InternetsTableSeeder::class); } }

Once you have written your seeder class, you may need to regenerate the Composer’s autoloader using the dump-autoload command.

composer dump-autoload

Then type the following command.

php artisan db:seed

It has generated 100 fake records inside the internets table. See the following image.

We have generated fake records using the faker library using Model Factory.

Testing Model Factories

Let’s create a new test by hitting the following command.

php artisan make:test InternetsTest

It will create a file called InternetsTest.php inside the tests >> Feature folder.

Write the testInternetsCreation() function inside the InternetsTest.php file.

<?php

// InternetsTest.php

namespace Tests\Feature;

use Tests\TestCase; use Illuminate\Foundation\Testing\WithFaker; use Illuminate\Foundation\Testing\RefreshDatabase;

class InternetsTest extends TestCase { /** * A basic feature test example. * * @return void */ public function testInternetsCreation() { $safeEmail = '[email protected]'; $domainName = 'rice.com'; $url = 'http://wintheiser.net/est-unde-nam-vel-non-eos-porro-sunt-rerum'; $ipv6 = '2626:5d6c:6597:1361:7106:5baa:def4:4270';

    $this-&gt;assertDatabaseHas('internets', [
        'safeEmail' =&gt; $safeEmail,
        'domainName' =&gt; $domainName,
        'url' =&gt; $url,
        'ipv6' =&gt; $ipv6,
    ]);
}

}

Laravel provides the variety of helpful tools to make it easier to test your database driven applications. First, you may use the assetDatabaseHas helper to assert that data exists in the database matching a given set of criteria. The assetDatabaseHas method and other helpers like it are for convenience. You are free to use any of PHPUnit’s built-in assertion methods to supplement your tests.

Now, we need to run the test. So go to the terminal and type the following command. Remember, your terminal is open inside the project root.

vendor/bin/phpunit tests/Feature/InternetsTest.php

See the output below.

Finally, Laravel Model Factories Tutorial With Example | Laravel 5.8 Seeding is over.

Originally published by Krunal  at appdividend.com

=========================

Thanks for reading :heart: If you liked this post, share it with all of your programming buddies! Follow me on Facebook | Twitter

☞ RESTful API with Laravel: Build a real API with Laravel

☞ Master Laravel - A php framework for Beginner to Advanced

☞ PHP with Laravel for beginners - Become a Master in Laravel

☞ Projects in Laravel: Learn Laravel Building 10 Projects

☞ Laravel 2019, the complete guide with real world projects

☞ Laravel for RESTful: Build Your RESTful API with Laravel

☞ Real Time Single Page Forum App with Pusher Laravel & vuejs

☞ Master Laravel PHP in 2019 for Beginners and Intermediate

laravel php web-development

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

PHP Web Application Development Company

As a top **PHP Web Application Development Company in USA**[https://www.dataeximit.com/php-development-services/](https://www.dataeximit.com/php-development-services/ "https://www.dataeximit.com/php-development-services/"), we at Data EximIT have...

PHP Website Development

Skenix Infotech is a leading PHP Web Development Company that helps companies get results with industry best practices. Get affordable PHP Development Services.

Hire Dedicated PHP Developer

Looking to hire affordable yet experienced PHP developers? **[Hire Dedicated PHP Developer](https://hourlydeveloper.io/hire-dedicated-php-developer/ "Hire Dedicated PHP Developer")**, who can convert your idea to reality, within the stipulated...

How to Hire Laravel Developers and How Much Does It Cost.

Want to make the most out of the latest Laravel technology? Here is your guide on how to hire the best Laravel developer, and at the right price. 

Advantages of Hiring PHP Developer for your Website Project

PHP - Hypertext pre-processor, a scripting language used by many people in developing web pages, but most of us are unaware even of the full form. To train someone and make them learn this whole language is as difficult and time-consuming as it is...