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 Image Upload Laravel 11 Vue 3 Example
How to Image Upload Laravel 11...

Hello, laravel web developer! In this article, we'll see how to image upload in laravel 11 vue 3. Here, we'...

Read More

May-27-2024

Carbon Add Months To Date In Laravel 9
Carbon Add Months To Date In L...

In this article, we will see carbon add months to date in laravel 9. Carbon provides the addMonth() and addMon...

Read More

Nov-18-2022

How to Create Custom Facade in Laravel 10
How to Create Custom Facade in...

Laravel, one of the most popular PHP frameworks, provides a powerful feature known as facades. Facades allow you to acce...

Read More

Sep-22-2023

How To Auto Select Country Using IP Lookup In jQuery
How To Auto Select Country Usi...

In this article, we will see how to auto select a country using IP lookup in jquery. Here, we will learn about auto...

Read More

May-15-2023