soyhuce/laravel-factories-extended

Extensions for Laravel model factories

0.1.1 2020-11-10 13:47 UTC

This package is auto-updated.

Last update: 2022-01-10 16:31:06 UTC


README

Latest Version on Packagist GitHub Workflow Status Total Downloads

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