Laravel Basic
Laravel Form
Laravel Database
Laravel Advance
A Factory in Laravel is a feature that allows you to easily create fake (dummy) data for your application models.
It is mainly used for:
id | name | email_verified_at | password | remember_token | created_at | updated_at |
---|
namespace App\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Factories\HasFactory; // 👈 Import class Employee extends Model { use HasFactory; // 👈 Add this line protected $fillable = ['name','email','email_verified_at','password','remember_token']; }
Use this command to generate a factory file:
php artisan make:factory EmployeeFactory --model=Employee
This generates a file in database/factories/:
use Illuminate\Support\Str; class EmployeeFactory extends Factory { public function definition(): array { return [ 'name' => $this->faker->name(), 'email' => $this->faker->unique()->safeEmail(), 'email_verified_at' => now(), 'password' => bcrypt('password'), 'remember_token' => Str::random(10), ]; } }
Employee::factory()->create();
Create one random data column in emoployees table
id | name | email_verified_at | password | remember_token | created_at | updated_at | |
---|---|---|---|---|---|---|---|
1 | Jermey West | freeda36@example.org | 2025-08-22 18:45:59 | $2y$12$VHalqym7PYrp.fWjvvXM6eW... | 4qmQEYkWRz | 2025-08-22 18:46:00 | 2025-08-22 18:46:00 |
Employee::factory()->count(10)->create();
Employee::factory()->make(); // returns instance but not saved
Laravel doesn’t have "types" officially, but based on use cases, we can group:
Used for defining different conditions of a model.
class EmployeeFactory extends Factory { public function definition(): array { return [ 'name' => $this->faker->name(), 'email' => $this->faker->unique()->safeEmail(), 'email_verified_at' => now(), 'password' => bcrypt('password'), 'remember_token' => Str::random(10), ]; } public function admin() { return $this->state(fn () => [ 'email' => 'admin@gmail.com', ]); } public function guest() { return $this->state(fn () => [ 'email' => 'admin@gmail.com', ]); } }
Condition based run function
Employee::factory()->admin()->create(); Employee::factory()->guest()->create();
User::factory() ->has(Profile::factory()) ->create();
User::factory() ->has(Post::factory()->count(5)) ->create();
User::factory() ->hasAttached(Role::factory()->count(3)) ->create();
Example: Comment
model morphs to Post
or Video
.
Comment::factory()->for(Post::factory(), 'commentable')->create();