Developer Snippet Diary

factory , faker, laravel

The factory is used to insert data to database for testing

1. Make factory

php artisan make:factory UserFactory;

it will create factory inside app\database\factories\UserFactory.php

Edit UserFactory.php

?php
namespace Database\Factories;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
class UserFactory extends Factory
{
    protected $model = \App\Models\User::class;
    public function definition()
    {
        return [
            'name' => fake()->name(),
            'email' => fake()->unique()->safeEmail(),
            'email_verified_at' => now(),
            'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
            'remember_token' => Str::random(10),
        ];
    }
}

RUN command:

php artisan tinker

then below command to enter fake record

\App\Models\User::factory()->create()

Multiple fake records

\App\Models\User::factory()->count(10)->create()

output:

 App\Models\User {#3833
    name: "Marcelina Marvin V",
    email: "brain.rath@example.net",
    email_verified_at: "2023-02-01 03:22:37",
    #password: "$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi",
    #remember_token: "qQ25j26FtW",
    updated_at: "2023-02-01 03:22:37",
    created_at: "2023-02-01 03:22:37",
    id: 3,
  }

FAKER:

echo $faker->name;   // 'Lucy Cechtelar';
echo $faker->address; //  // "426 Jordy Lodge
echo $faker->text;   // Cartwrightshire, SC 88120-6700"

randomDigit             // 7
randomDigitNot(5)       // 0, 1, 2, 3, 4, 6, 7, 8, or 9
randomDigitNotNull      // 5
randomNumber($nbDigits = NULL, $strict = false) // 79907610
randomFloat($nbMaxDecimals = NULL, $min = 0, $max = NULL) // 48.8932
numberBetween($min = 1000, $max = 9000) // 8567
randomLetter            // 'b'
randomElements($array = array ('a','b','c'), $count = 1) // array('c')
randomElement($array = array ('a','b','c')) // 'b'
shuffle('hello, world') // 'rlo,h eoldlw'
shuffle(array(1, 2, 3)) // array(2, 1, 3)
numerify('Hello ###') // 'Hello 609'
lexify('Hello ???') // 'Hello wgt'
bothify('Hello ##??') // 'Hello 42jz'
asciify('Hello ***') // 'Hello R6+'
regexify('[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}'); // sm0@y8k96a.ej

For details visit

https://github.com/fzaninotto/Faker

 

Posted by: R GONDAL
Email: rizikmw@gmail.com