• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
Tutsplanet

Tutsplanet

Free Technical and Blogging Resources

  • Home
  • Web Hosting
  • Programming
  • Plugins
  • Twitter Trends
  • Tools
  • About Us

Programming TagsLaravel

How to use Faker with Laravel ?

Aug 11, 2021 Editorial Staff

Share
Tweet
Share
3 Shares

As the name suggests Faker is a PHP library that generates fake data for you. Why do we need fake data? Good question, we need fake data to simulate a development environment, which looks very close to real data. Sometimes developers need to have a bulk amount of dummy data, to test a feature like pagination or performance impact of a huge listing, as adding data by hand is not a viable solution. So we use faker to generate multitudes of data for testing.

In today’s article, we are demonstrating how to install Faker in your Laravel project and how to use Faker in your latest Laravel project. Basically, we don’t need to install it in  Laravel Faker as it’s shipped with Laravel. Follow the steps described below to use Faker in your Laravel project.

Step #1 Create a model and migration

In our tutorial, we are considering you have a customer database that needs to be filled with fake data.

Run the below command to create the Laravel model and migration

php artisan make:model Customer -m

The above command will generate a model in App/Models folder and a migration file in the database/migrations folder.

Here -m flag creates for a model with migration.

In the migration file, we will add firstname, lastname, email, phone number, country for a customer record.

So we prepared our migration file as below

 public function up()
    {
        Schema::create('customers', function (Blueprint $table) {
            $table->id();
            $table->string('firstname');
            $table->string('lastname');
            $table->string('email');
            $table->string('phone');
            $table->string('country');
            $table->timestamps();
        });
    }

And your model will look like below

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Customer extends Model
{
    use HasFactory;

    protected $fillable = [
        'firstname',
        'lastname',
        'email',
        'phone',
        'country',
    ];
}

You may have noticed that I used a protected $fillable property and certain values filled in it. This is Laravel’s fillable property, which will safeguard Laravel mass assign. But you can read a detailed article here about fillable in Laravel.

Now run the migration to create the table in the database.

php artisan migrate

After migration, you can see a blank customers table is created in the database.

How-to-use-Faker-with-Laravel

Step #2: Create a Database Seeder with Faker

This is the main step of our tutorial as we create a seeder and this seeder will be running faker functions to create fake data.

Create seeder using the below command

php artisan make:seeder CustomerSeeder

You can see a new file is created in database/seeders folder with name CustomerSeeder.php.

<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use Faker\Factory as Faker;
use App\Models\Customer;

class CustomerSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $faker = Faker::create();

        for($i = 1 ; $i <= 10 ; $i++){
            Customer::create([
                'firstname' => $faker->firstName,
                'lastname'  => $faker->lastName,
                'email'     => $faker->email,
                'phone'     => $faker->phoneNumber,
                'country'   => $faker->country
            ]);
        } 


    }
}

Run the below command to generate fake data using Faker

php artisan db:seed --class=CustomerSeeder

You may have noticed that we have used a for loop of 10 iterations to insert 10 records in the database. You can increase the number of iterations to insert a different number of records. For example, if you want to test 10k records, you may replace 10000 in the position of $i, then it will create 10000 records for you.

How-to-use-Faker-with-Laravel01

That’s it hope you have enjoyed the article.

Did this post help you?
Tutsplanet brings in-depth and easy tutorials to understand even for beginners. This takes a considerable amount of work. If this post helps you, please consider supporting us as a token of appreciation:
  • Just want to thank us? Buy us a Coffee
  • May be another day? Shop on Amazon using our links.
    Your prices won't change but we get a small commission.

Editorial Staff

Editorial Staff at Tutsplanet is a dedicated team to write various tutorials about subjects like Programming, Technology and Operating Systems.

View all posts by Editorial Staff

Primary Sidebar

Quick Links

  • Top 21 Website Ideas To Make Money Online in 2021
  • A Simple YouTube Video Downloader Script in PHP
  • The 50 Most Useful jQuery Plugins for Frontend Development
  • Replace “\n” with new line characters, using Notepad++
  • Using Third-Party Libraries in Codeigniter
  • Upload Multiple Images and Store in Database using PHP and MySQL.
  • Hierarchical Tree view Category Example in Laravel
  • Laravel Image Intervention Tutorial With Example
  • How to import sql file in MySQL database using PHP?
  • Free VAT Calculator Online

Subscribe

* indicates required

Search Here

Share

   

Hot topics

  • Replace “\n” with new line characters, using Notepad++ 17 views
  • A Simple YouTube Video Downloader Script in PHP 17 views
  • Add FTP/SFTP in Visual Studio Code 16 views
  • Open a URL in a new tab using JavaScript 15 views
  • Auto Login in PuTTY with a password 12 views
  • How to enter new line in Microsoft Teams? 12 views
  • PHP: Implode () with quotes 10 views
  • Hierarchical Tree view Category Example in Laravel 10 views
  • Simple PHP Shopping Cart 9 views
  • Laravel: Download files to storage from SFTP 8 views

Categories

  • Design & Development
  • Drupal
  • Facebook
  • General
  • How To
  • ios
  • Javascript
  • Linux
  • Magento
  • Marketing
  • News
  • PHP
  • Plugins
  • Programming
  • Snippets List
  • Social Media
  • Softwares
  • Themes
  • Tips
  • Wordpress
  • YouTube

Copyright © 2023 · Planet on Genesis Framework · Powered By BunnyCDN . Network wallpapernoon.com