Skip to content

[9.x] Add ->set() method to factory - #41890

Merged
taylorotwell merged 3 commits into
laravel:9.xfrom
ralphjsmit:9.x
Apr 8, 2022
Merged

[9.x] Add ->set() method to factory#41890
taylorotwell merged 3 commits into
laravel:9.xfrom
ralphjsmit:9.x

Conversation

@ralphjsmit

@ralphjsmit ralphjsmit commented Apr 8, 2022

Copy link
Copy Markdown
Contributor

Lately I've been writing unit-tests for the models of an application that did not have many tests yet. In that application many scopes were used.

I noticed that I was often creating models like this, where you just need to make one little change every time:

EloquentModel::factory()
    ->create(['name' => 'foo']);

EloquentModel::factory()
    ->someMethod()
    ->create(['country' => 'NL']);

I figured out that the tests would look a lot cleaner if we could just get rid of those single-item arrays, so I came up with a small method called ->set(). This method is in my eyes easier and more expressive than ->create(['foo' => 'bar']), because it is immediately clear that we're setting only a single property here.

EloquentModel::factory()
    ->set('name', 'foo')
    ->create();

EloquentModel::factory()
    ->someMethod()
    ->set('country', 'NL')
    ->create();

Another option would be to name the method ->put(), in line with the similar collection method (but personally I prefer ->set()).

@taylorotwell
taylorotwell merged commit ce3d25c into laravel:9.x Apr 8, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants