Download the PHP package thettler/laravel-factory-classes without Composer
On this page you can find all versions of the php package thettler/laravel-factory-classes. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download thettler/laravel-factory-classes
More information about thettler/laravel-factory-classes
Files in thettler/laravel-factory-classes
Package laravel-factory-classes
Short Description A Package to easy create Factory Classes for your tests with a fluent api and automatic auto completion
License MIT
Homepage https://github.com/christophrumpel/laravel-factories-reloaded
Informations about the package laravel-factory-classes
Welcome to Laravel Factory Classes 👋
Laravel Factory Classes is a package to help you creating Models with data through Factory Classes with a fluent API and automatic auto completion for your tests, seeder or everywhere you might want them.
:bulb: Why would you want to use this package?
Creating Factories for all your Models can get pretty messy sometimes. It lacks autocomplete, you often have to know about
the business logic of the Model to get it to a specific state.
A Factory class solves those problems. Every Model has its own Factory which contains everything necessary to create and fill it with data.
You can simply use the API of the Factory to instantiate, save or alter the Model.
To know more about this topic I suggest this blog post from sticher.io.
Example
Think of a use case where we have a concert Model with a venue (belongsTo), supporting acts (belongsToMany), headliners (belongsToMany) and some other attributes we don't care about in this example. With normal Factories you would do something like this to create a concert:
With this package it would look like this:
and the Factory class looks like this:
:scroll: Features
- Create Models and save them to the DB
- Make Models without saving them to the DB
- Create Models with relations
- Create all the Factories you need with one command (
--recursive
) - Automatically generated dummy data for your Models
- Also usable outside of test without dummy data generation
- Extract Model creation logic to it's own class
- Full control over relations and attributes at any time
:computer: Installation
You can install the package via composer:
To publish the config file run:
It will provide the package's config file where you can define the path of your Models, the path of the generated Factories, as well as the generated Factories namespace
:rocket: Getting Started
The Quick Way
To create a new Factory you can use the following command:
This will prompt you a list with Models, it knows where your models live from your config. Here you choose the Model you want to create.
This will give you a new Factory
under the App\Factories
namespace and add all of its relations automatically if you type hint them inside your
Model with their return value. More About Relations.
To Understand what this Command generated for you read the Manual Guide
Additional Arguments And Options
If you don't want to select your Model from a list, you can pass the class name of a Model in your Model path as an argument and your Factory will immediately be created for you:
By default, this command will stop and give you an error if a Factory you're trying to create already exists. You can overwrite an existing Factory using the force option:
A quick way to build a lot of new Factories is to use the --recursive
flag. It will then go through all the relations of the chosen class and create Factories for them as well if there aren't any already.
If you don't want the relation methods automatically created, you can use this flag:
You can also overwrite the config using the command:
--models_path=app/models
--factories_path=path/to/your/factories
--factories_namespace=Your\Factories\Namespace
The Manual Way
To create your first FactoryClass
you simply create a normal PHP Class and extend the abstract Thettler\LaravelFactoryClasses\FactoryClass
Class.
This Class requires you to define 3 Methods and one attribute:
-
First you have to add a
protected string $model
attribute to the factory. It contains the reference to the Model the Factory should create. So for example the standardUser
Class Laravel ships with: -
After you told the Factory which Model it should create you have to define a
public create()
function. It expects a parameter$extra
which is an array with the default value of an empty array. More on the purpose of$extra
later. Here you should also typehint the Model Class as the return value. This will give you autocomplete in the most editors. Finally you call and return the$this->createModel($extra)
method. This method will take care of creating the Model for you. You still got the freedom to alter the Model after its creation or completely create it on your own. So with ourUser
Class it looks like this: -
Now you have to add a
public make()
function. It's pretty much the same as withcreate()
, but here you call the$this->makeModel($extra)
method instead of$this->createModel($extra)
. We will talk about the difference betweencreate()
andmake()
in a moment. So with ourUser
Class it looks like this: - The last method you have to add is
protected fakeData()
. This method gets aFaker
instance as a parameter and expects you to return an Array. ThefakeData()
method is used to generate default data for your Models. It returns an associative array with the name of the attribute as key and the value you want to set.
So with ourUser
Class it looks like this:
Now you are good to go and have created your first FactoryClass. The complete Class now looks like this:
Using Factories
Creating/Making Models
Now that you have created your FactoryClass
you'll want to use it. To instantiate your FactoryClass
use the static new()
method.
To create and save a Model to the Database now call the create()
method. This will create a Model with the data you have defined
inside of the fakeData()
If you don't want to store the Model in the database use the make()
method.
In case you need more than one Model you can use the createMany()
and makeMany()
methods. Both take an int as parameter, which indicates how many Models
should be created, and return a Collection
with the Models.
Changing Data
In most cases you want to change some attributes depending on the situation and don't want to use all of the fakeData
. This
Package gives you 3 options for changing the data that is used to create the Model.
-
Use the
addData()
method. This method takes the name of an attribute as the first parameter and the value which should be set as the second one. - The second option is to use the
data()
method. This method takes an array of key value pairs which represent the attributes and their values. This method will also overwrite all of the previous set data
:warning:
data()
andaddData()
will automatically give you a new instance of the Factory to prevent side effects
- The Last option is using the
$extra
parameter on thecreate()
,createMany()
,make()
ormakeMany()
methods. This will overwrite the previous data with the same key.
But the $extra
for createMany()
and makeMany()
are a little bit different from create()
and make()
.
Here you can also pass a nested array to give the Models in the Collection different data.
:sparkles: Tip:
If you want a more readable API, you can add little helper setters to your Factory class, like this:
Relations
Creating Models with relations is often a little bit tedious. This Package has got your back with a simple, yet powerful relation system that uses your already defined relations on the Model.
All relations are working pretty much the same, they take the relation name as first Parameter and a FactoryClass
or Model
as the second one.
They also have a third parameter that lets you hook into the relation and modify its behavior but we'll save that for the
Advanced part for now.
If you provide a FactoryClass
as second parameter the relation will create a new Model from the FactoryClass
every time you call create()
, createMany()
,make()
or makeMany()
and attach it to the Model Relation.
:warning: Same as with
data()
andaddData()
all relation methods will give you a new instance of the Factory to prevent side effects.
For all the examples we assume that the Model has a Company relation that is called company
.
HasOne
HasMany
The hasMany()
method takes an array of FactoryClasses
or Models
as second parameter.
BelongsTo
BelongsToMany
Just like hasMany()
, belongsToMany()
takes an array of FactoryClasses
or Models
:
If you want to add pivot data to your belongsToMany()
relation, you can use the third parameter. Its a callback
that gives you an Instance of BelongsToManyFactoryRelation
. On this class you can call the pivot()
method and return it again
to add your pivot data.
You can find more about the third parameter in the Advanced part.
MorphTo
MorphOne
:sparkles: Tip:
On your FactoryClass
create little helpers with default values for your relations so you can call them without explicitly
giving them a FactoryClass
or Model:
or for multiple relations:
The command will generate those methods automatically for you if you define a return type on your Model for your Relations.
:warning: The automatic method creation does not work for
MorphTo
relations
Disable Fake Data generation
If you don't want fake data to be generated for your Model you can use the withoutFakeData()
method on the Factory.
:hammer: Advanced
Customize Relations
Every relation has its dedicated class that takes care of creating the relations. You can hook into the class and modify it by using
the third parameter of the relation functions.
It is a Callable that receives an instance of FactoryRelation
and returns an instance of FactoryRelation
.
Using own Relations
If you need more complex Relations you can write your own FactoryRelations
and use them in your Factories.
To do so use the with()
method on your FactoryClass
and Pass your relation as first Parameter through.
To Create your FactoryRelation
make a new PHP Class and Extend the FactoryRelation
class. Define the Abstract methods and you are good to
go. For more examples look under src/Relations
.
Run tests
Author
👤 Tobias Hettler
- Website: stageslice.com
- Twitter: @TobiSlice
- Github: @thettler
🤝 Contributing
Contributions, issues and feature requests are welcome!
Feel free to check issues page.
Show your support
Give a ⭐️ if this project helped you!
📝 License
Copyright © 2020 Tobias Hettler.
This project is MIT licensed.
This README was generated with ❤️ by readme-md-generator
All versions of laravel-factory-classes with dependencies
illuminate/support Version ^6.0|^7.0
laravel/framework Version ^6.0|^7.0
christophrumpel/laravel-command-file-picker Version ^0.0.7
fzaninotto/faker Version ^1.4