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

Advantages of Hiring PHP Developer for your Website Project

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

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 to learn the language yourself. That’s why PHP developers are there to make your life easy. This article will give us the advantages and requirements of Hire PHP Developer for our very own website project.

First of all, let us understand the value the right developer brings to the project and why it is important for your business.

A website is a major component of any company/business and is very important for its face value, the way it represents the company on the internet is critical for any business to succeed. This is the reason why companies are looking for PHP developers who can develop their webpage.

If you're planning to do an online business, your PHP programmer will be the first person to transfer your thinking onto the webpage. You should, therefore, employ developers from PHP to make your hypothetical idea a reality.

With this software programming language, PHP developers all-around can easily build website frameworks, web content management systems, web template systems, and various other web-based designs.

Some of the reasons why we need to outsource these developers are:

Not everyone is the best in each field, all of us have our specific skills and talents hence, PHP developers are also the best at what they do. The time and money spent on the training of the in house employees would be saved if the professional PHP developers are hired. Instead of multitasking, if the employees were to focus on what they’re good at it would increase productivity too.

The PHP developers would be much more professional than the in-house workers. It would lead to the seriousness of work. Hence, on-time delivery is guaranteed with hired PHP developers.

In addition to these benefits, you would also be able to track your project through every stage in constant communication with your online team. These advantages make it incredibly popular and smart to hire a PHP developer.

The PHP developers have in-depth knowledge of PHP, HTML and various frameworks in terms of technical capabilities. Hiring PHP developers are advised to give your website a professional look based on PHP.

Much of web success depends on the involvement of social media. The developer can add to your social networking pages a feature that explicitly redirects visitors. In addition, SEO experts also suggest better connections to the website's social network.

Just like a tailor stitches our dresses according to our preferences and is ready to make last-minute changes. A PHP developer will also be available at the nick of your call to make the website just the way you want it to be and have a customized solution for every problem.

Read also: Why & How to Hire Dedicated PHP Developer

At some point in your business, you’re going to have problems regarding your webpage due to the rapidly changing technology, instead of struggling with ideas like these and not being able to come up with an appropriate solution a PHP web developer could help us with our problems just like any technician would help us with the problems we face in our offices or any architect would help us with designing the structure of a building or any interior designer would help us with setting up our home. The PHP development company are hubs of workers who would help us overcome these problems and are always there.

Source by

Hire PHP Developer and Web Developer for your Online Business

Hire PHP Developer and Web Developer for your Online Business

PHP is widely used open-source scripting language it helps in making dynamically easy your websites and web application. Mobiweb Technology is your best technical partner and offering you solution for any kind of website and application...

PHP is widely used open-source scripting language it helps in making dynamically easy your websites and web application. Mobiweb Technology is your best technical partner and offering you solution for any kind of website and application development. To hire PHP developer and web developer at affordable prices contact Mobiweb Technology via [email protected]

Laravel Framework Development Services | Laravel Web Development

CMARIX is leading Laravel Web application Development Service Provider with the track record of implementing diverse high-performance Laravel web applications with skilled Laravel developer team for clients across the globe<a href="https://www.cmarix.com/laravel-framework-development-services.html?utm_source=SB" target="_blank">.Continue</a>

CMARIX is leading Laravel Web application Development Service Provider with the track record of implementing diverse high-performance Laravel web applications with skilled Laravel developer team for clients across the globe.Continue