Home > Back-end >  Laravel what is use HasFactory?
Laravel what is use HasFactory?

Time:09-05

I created a model in Laravel. I always noticed the default would be use HasFactory. May I know what exactly does it work. In my understanding from reading documentation, it is for linking to database (I guess?) But I still don't understand how it works exactly.

CodePudding user response:

HasFactory is not to link to the database. It is a trait that links a Eloquent model to a model factory.

Factories are normally used in testing when wanted test-data for a specific model.

You can read more about factories in Laravel here: https://laravel.com/docs/9.x/database-testing#model-factories and here: https://laravel.com/docs/9.x/eloquent-factories

The trait ensures that you can instantiate a factory like this:

User::factory()->create();

In older versions of Laravel the trait was not used, and instead a factory had to be instantiated by the global factory helper like this factory(User::class)->create(); but that caused a lot of problems with intellisense in IDE's.

  • Related