4

Using Factory sequences in Laravel

 2 years ago
source link: https://freek.dev/2097-using-factory-sequences-in-laravel
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Oh Dear is the all-in-one monitoring tool for your entire website. We monitor uptime, SSL certificates, broken links, scheduled tasks and more. You'll get a notifications for us when something's wrong. All that paired with a developer friendly API and kick-ass documentation. O, and you'll also be able to create a public status page under a minute. Start monitoring using our free trial now.

Using Factory sequences in Laravel

Original – Oct 18th 2021 by Brent Roose – 1 minute read

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!

Stay up to date with all things Laravel, PHP, and JavaScript.

Follow me on Twitter. I regularly tweet out programming tips, and what I myself have learned in ongoing projects.

Every two weeks I send out a newsletter containing lots of interesting stuff for the modern PHP developer.

Expect quick tips & tricks, interesting tutorials, opinions and packages. Because I work with Laravel every day there is an emphasis on that framework.

Rest assured that I will only use your email address to send you the newsletter and will not use it for any other purposes.

Comments #


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK