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
Scaling for Success: Comparing cPanel Hosting with Easy Scalability
Scaling for Success: Comparing...

In today's digital landscape, your website serves as your storefront, your testimonial, and your voice. As your busi...

Read More

Jun-28-2024

How To Create Dynamic Pie Chart In Laravel 8
How To Create Dynamic Pie Char...

In this article, we will see how to create a dynamic pie chart in laravel 8. Pie charts are used to represent...

Read More

Oct-02-2020

How to Install PHP Soap Extension in Ubuntu 23.04
How to Install PHP Soap Extens...

Hey fellow developers! Today, let's tackle the installation of the PHP SOAP extension on our Ubuntu 23.04 systems. I...

Read More

Jan-31-2024

Laravel 9 Has Many Through Relationship Example
Laravel 9 Has Many Through Rel...

In this article, we will see that laravel 9 has many through relationship example. hasManyThrough relationship is diffic...

Read More

Apr-04-2022