Laravel 5: Creating Eloquent Models for Testing With factory

April 14, 2018 —John Koster

The factory function is used to create Eloquent models, and is generally used when testing an application to generate sample data.

#Signature

The signature of the factory function is:

1function factory(
2 $class
3);
4 
5function factory(
6 $class,
7 string $modelName
8);
9 
10function factory(
11 $class,
12 int $numberOfModels
13);
14 
15function factory(
16 $class,
17 string $modelName,
18 int $numberOfModels
19);

#Example Use

The factory method can generally take one of four forms:

1// Return an instance of the 'User' model.
2$user = factory('App\User')->make();
3 
4// Return two instances of the 'User' model.
5$users = factory('App\User', 2)->make();
6 
7// Return one instance of the 'User' model, with some
8// modifications that were defined earlier and
9// bound to the 'admin' description.
10$adminUser = factory('App\User', 'admin')->make();
11 
12// Return two instances of the 'User' model, with some
13// modifications that were defined earlier and
14// bound to the 'admin' description.
15$adminUsers = factory('App\User', 'admin', 2)->make();

Some absolutely amazing
people

The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.