+1 vote
in Laravel by
What are factories in Laravel?

1 Answer

0 votes
by

Factories are a way to put values in fields of a particular model automatically. Like, for testing when we add multiple fake records in the database, we can use factories to generate a class for each model and put data in fields accordingly. Every new laravel application comes with database/factories/UserFactory.php which looks like below:

<?php

namespace Database\Factories;

use App\Models\User;

use Illuminate\Database\Eloquent\Factories\Factory;

use Illuminate\Support\Str;

class UserFactory extends Factory

{

   /**

    * The name of the factory's corresponding model.

    *

    * @var string

    */

   protected $model = User::class;

   /**

    * Define the model's default state.

    *

    * @return array

    */

   public function definition()

   {

       return [

           'name' => $this->faker->name,

           'email' => $this->faker->unique()->safeEmail,

           'email_verified_at' => now(),

           'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password

           'remember_token' => Str::random(10),

       ];

   }

}

We can create a new factory using php artisan make:factory UserFactory --class=User.

The above command will create a new factory class for the User model. It is just a class that extends the base Factory class and makes use of the Faker class to generate fake data for each column. With the combination of factory and seeders, we can easily add fake data into the database for testing purposes.

Related questions

0 votes
asked Jun 27, 2023 in Laravel by SakshiSharma
+1 vote
asked Jul 10, 2021 in Laravel by SakshiSharma
...