Using Factory sequences in Laravel
One of the things I really like about modern Laravel projects, are the new model factories introduced in Laravel 8.
When writing complex tests, you often need quite a lot of setup, and features like factories, and especially factory sequences make that setup significantly easier to do. Take a look at this example:
$blogPosts = BlogPost::factory()
->count(3)
->published()
->sequence(
['title' => 'Parallel php'],
['title' => 'Fibers'],
['title' => 'Thoughts on event sourcing'],
)
->create();
This factory call will make three blog posts. Each post will have a published state, but also a different title, thanks to that sequence method.
Did you know that you even can use array destructuring to immediately get all three blogposts in separate variables?
[$a, $b, $c] = BlogPost::factory()
->count(3)
->published()
->sequence(
['title' => 'Parallel php'],
['title' => 'Fibers'],
['title' => 'Thoughts on event sourcing'],
)
->create();
Pretty neat! These model factories are a great addition to Laravel. Oh and, if you were wondering, the Laravel Idea plugin has full autocomplete support for them in PhpStorm as well!
What are your thoughts on "Using Factory sequences in Laravel"?