AppDividend
Latest Code Tutorials

Laravel Model Factories Tutorial With Example | Laravel 5.8 Seeding

1

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.

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 create_internets_table.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.

Related Posts
1 of 43
<?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

 

Laravel Model Factories Tutorial With Example | Laravel 5.8 Fake Data

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

 

Laravel Model Factories Tutorial With Example | Laravel 5.8 Seeding

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 = 'lyric.heidenreich@example.org';
        $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->assertDatabaseHas('internets', [
            'safeEmail' => $safeEmail,
            'domainName' => $domainName,
            'url' => $url,
            'ipv6' => $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.

 

Testing Model Factories

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

1 Comment
  1. yokasre says

    Very helpful Tutorial. Thanks a lot.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.