Laravel Factories Reloaded


June 24th, 2020


Laravel Factories Reloaded is a package by Christoph Rumpel that generates class-based model factories that you can use instead of the factory files Laravel provides.

Here are the main benefits of this package as provided in the readme:

  • use the features you already love from Laravel factories (create, make, times, states)
  • automatically create new class factories for specific or All your models
  • automatically import defined default data and states from your Laravel factories
  • and many more…

Here are some examples of how you might use the class-based factories provided by this package:

1// Create a new record in the database
2$user = UserFactory::new()->create();
4// Make a new model without peristing to the database
5$user = UserFactory::new()->make();
7// Use a factory state
8$recipe = UserFactory::new()
9 ->active()
10 ->create();
12// Relations
13$recipe = RecipeFactory::new()
14 ->with(Group::class, 'group')
15 ->with(Ingredient::class, 'ingredients')
16 ->with(Ingredient::class, 'ingredients', 3)
17 ->create();

You might be asking, “what is the benefit of using class-based factories?” The project’s readme mentions the following benefits of using this package:

  • They give you much more flexibility on how to create your model instances.
  • They make your tests much cleaner because you can hide complex preparations inside the class.
  • They provide IDE auto-completion, which you do not have with Laravel factories.

Learn More

You can learn more about this package, get full installation instructions, and view the source code on GitHub at christophrumpel/laravel-factories-reloaded.

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.