How to Generate Fake Data using Tinker in Laravel 11

Websolutionstuff | May-22-2024 | Categories : Laravel

Hello, laravel web developers! In this article, we'll see how to generate fake data using Tinker in laravel 11. Here, we'll create dummy records for testing purposes in laravel 11. All Laravel applications include Tinker by default.

You can install Tinker using Composer if you have previously removed it from your application.

Tinker allows you to interact with your entire Laravel application on the command line, including your Eloquent models, jobs, events, and more.

Laravel 11 Generate Dummy Data using Tinker

Generate Fake Data in Laravel 11

To enter the Tinker environment, run the tinker Artisan command:

php artisan tinker

 

Generate Dummy Users:

This by default created a factory of Laravel. 

database/factories/UserFactory.php

User::factory()->count(10)->create()

 

Create Custom Factory

Now, we'll create a factory for creating dummy records. Instead of manually specifying the value of each column, Laravel allows you to define a set of default attributes for each of your Eloquent models using model factories.

app/Models/User.php

<?php
    
namespace App\Models;
    
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
    
class User extends Model
{
    use HasFactory;
    
    protected $fillable = [
        'name', 'email', 'email_verified_at'
    ];
}

Next, create a custom factory using the following command.

php artisan make:factory UserFactory --model=User

database/factories/UserFactory.php

namespace Database\Factories;
 
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
 
/**
 * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\User>
 */
class UserFactory extends Factory
{
    /**
     * The current password being used by the factory.
     */
    protected static ?string $password;
 
    /**
     * Define the model's default state.
     *
     * @return array<string, mixed>
     */
    public function definition(): array
    {
        return [
            'name' => fake()->name(),
            'email' => fake()->unique()->safeEmail(),
            'email_verified_at' => now(),
            'password' => static::$password ??= Hash::make('password'),
            'remember_token' => Str::random(10),
        ];
    }
 
    /**
     * Indicate that the model's email address should be unverified.
     */
    public function unverified(): static
    {
        return $this->state(fn (array $attributes) => [
            'email_verified_at' => null,
        ]);
    }
}

Via the fake helper, factories have access to the Faker PHP library, which allows you to conveniently generate various kinds of random data for testing and seeding.

Faker is a PHP library that generates fake data for you. 

Person:

title($gender = null|'male'|'female')     // 'Ms.'
titleMale()                               // 'Mr.'
titleFemale()                             // 'Ms.'
suffix()                                  // 'Jr.'
name($gender = null|'male'|'female')      // 'Dr. Zane Stroman'
firstName($gender = null|'male'|'female') // 'Maynard'
firstNameMale()                           // 'Maynard'
firstNameFemale()                         // 'Rachel'
lastName()                                // 'Zulauf'

 

Address:

cityPrefix()                       // 'Lake'
secondaryAddress()                 // 'Suite 961'
state()                            // 'NewMexico'
stateAbbr()                        // 'OH'
citySuffix()                       // 'borough'
streetSuffix()                     // 'Keys'
buildingNumber()                   // '484'
city()                             // 'West Judge'
streetName()                       // 'Keegan Trail'
streetAddress()                    // '439 Karley Loaf Suite 897'
postcode()                         // '17916'
address()                          // '8888 Cummings Vista Apt. 101, Susanbury, NY 95473'
country()                          // 'Falkland Islands (Malvinas)'
latitude($min = -90, $max = 90)    // 77.147489
longitude($min = -180, $max = 180) // 86.211205

 

Phone Number:

phoneNumber()              // '827-986-5852'
phoneNumberWithExtension() // '201-886-0269 x3767'
tollFreePhoneNumber()      // '(888) 937-7238'
e164PhoneNumber()          // '+27113456789'

 

Text:

realText($maxNbChars = 200, $indexSize = 2)
// "And yet I wish you could manage it?) 'And what are they made of?' Alice asked in a shrill, passionate voice. 'Would YOU like cats if you were never even spoke to Time!' 'Perhaps not,' Alice replied."

realTextBetween($minNbChars = 160, $maxNbChars = 200, $indexSize = 2)
// "VERY short remarks, and she ran across the garden, and I had not long to doubt, for the end of the bottle was NOT marked 'poison,' it is right?' 'In my youth,' Father William replied to his ear."

 


You might also like:

Recommended Post
Featured Post
Multiple Row Grouping Datatables jQuery
Multiple Row Grouping Datatabl...

In this article, we will see how to row group in datatable in jquery. Datatables doesn't have row grouping buil...

Read More

Jun-04-2022

How To Add Datepicker In Angular 15 Material
How To Add Datepicker In Angul...

In this tutorial, I will guide you through the process of adding a datepicker component to your Angular 15 application u...

Read More

Jun-28-2023

How To Validate Email Using jQuery
How To Validate Email Using jQ...

In this article, we will see how to validate email using jquery. we will use regular expression(regex) for email va...

Read More

Nov-09-2022

How To File Upload In Angular 15 Example
How To File Upload In Angular...

As an Angular 15 developer, I understand the significance of incorporating file upload functionality into web applicatio...

Read More

Jun-19-2023