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
How To Block IP Address In Laravel 10
How To Block IP Address In Lar...

In this article, we will see how to block IP addresses in laravel 10. Here we will learn about how to restrict...

Read More

May-17-2023

How To Disable Dates After Week In jQuery Datepicker
How To Disable Dates After Wee...

In this tutorial, we will see how to disable dates after a week in jquery datepicker. In the date picker, we can di...

Read More

Jun-29-2022

Laravel 8 Class NumberFormatter Not Found
Laravel 8 Class NumberFormatte...

In this example we will see example of laravel 8 class numberformatter not found. For numberformatter we need PHP 5...

Read More

Dec-27-2021

Laravel 8 Group By Query Example
Laravel 8 Group By Query Examp...

In this example we will see laravel 8 group by query example. how to use group by in laravel 8. As you might expect...

Read More

Nov-29-2021