soyhuce / laravel-factories-extended
Extensions for Laravel model factories
Requires
- php: ^7.3|^8.0
- illuminate/database: ^8.0
- illuminate/support: ^8.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^2.17
- mockery/mockery: ^1.4
- orchestra/testbench: ^6.0
- phpunit/phpunit: ^9.4
- soyhuce/next-ide-helper: ^0.3.0
Suggests
- soyhuce/next-ide-helper: Laravel ide helper rebuilt under steroids, to document Factory extensions
This package is auto-updated.
Last update: 2024-12-10 22:38:17 UTC
README
This package provides extensions for Laravel 8 Model Factories
Installation
You should install this package using composer :
composer require soyhuce/laravel-factories-extended
You're done !
Usage
Your model Factory has to extend Soyhuce\LaravelFactoriesExtended\Factory
:
<?php use Soyhuce\LaravelFactoriesExtended\Factory; class UserFactory extends Factory { // Same like usual factories }
More documentations about factories here
Extensions
of and dynamic of
Sometimes we need to use both a model and its related models in a test. With of
, you can define a relation between the created models and an existing model :
$user = UserFactory::new()->create(); $posts = PostFactory::times(3)->of($user)->create();
In case the relation cannot be guessed directly from the model, we can define it explicitly :
$posts = PostFactory::times(3)->of($user, 'author')->create();
You can also use of
with MorphTo
relations :
$comments = CommentFactory::times(3)->of($post, 'commentable')->create();
and with multiple models :
$comments = CommentFactory::times(3)->of($post, 'commentable')->of($user, 'user')->create();
You can use dynamic of to define the relation name :
$user = UserFactory::new()->create(); $post = PostFactory::new()->ofAuthor($user)->create(); $comments = CommentFactory::times(3)->ofCommentable($post)->ofUser($user)->create();
If you use soyhuce/next-ide-helper
(version ^0.2.4), we provide for you a factory extension to automatically add dynamic of methods. You just have to add Soyhuce\LaravelFactoriesExtended\DynamicOfResolver::class
in your next-ide-helper.factories.extensions
config.
Contributing
You are welcome to contribute to this project ! Please see CONTRIBUTING.md.
License
This package is provided under the MIT License