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
Laravel 11 Install Yajra Datatable Example
Laravel 11 Install Yajra Datat...

In this tutorial, we'll explore an example of installing Yajra Datatable in Laravel 11. In every project, it's e...

Read More

Apr-10-2024

How Generate PDF From HTML View In Laravel
How Generate PDF From HTML Vie...

In this example, I will teach you how to generate PDF files from an HTML view in laravel. For generating PDF files I wil...

Read More

Jun-01-2020

How To Create Parallax Scrolling Effect Using jQuery
How To Create Parallax Scrolli...

In this article, we will see how to create a parallax scrolling effect using jquery. Parallax scrolling is a websit...

Read More

May-04-2022

Laravel 8 One To Many Polymorphic Relationship
Laravel 8 One To Many Polymorp...

In this tutorial we will learn about laravel 8 one to many polymorphic relationship. A one-to-many polymorphic rela...

Read More

Nov-19-2021