In Laravel 5.3.17, Model Factories now includes states

News

October 6th, 2016

laravel-5.3.png

New in Laravel 5.3.17 is an improvement to Model Factories that you allows to define different “states” for a factory.

For example pretend you have a simple faker for creating a User:

1$factory->define(App\User::class, function (Faker\Generator $faker) {
2 return [
3 'name' => $faker->name,
4 'email' => $faker->safeEmail,
5 ];
6});

Now you want to have the ability to define an administrator:

1$factory->state(\App\User::class, 'admin', function (\Faker\Generator $faker) {
2 return [
3 'is_admin' => 1,
4 ];
5});

Then a moderator flag:

1$factory->state(\App\User::class, 'moderator', function (\Faker\Generator $faker) {
2 return [
3 'is_moderator' => 1,
4 ];
5});

With these three set you can now call them like this:

1// Create 5 users
2factory(\App\User::class, 5)->create();
3
4// Create 5 Admins
5factory(\App\User::class, 5)->states('admin')->create();
6
7// Create 5 Moderators
8factory(\App\User::class, 5)->states('moderator')->create();
9
10// Create 5 Admins that are also moderators
11factory(\App\User::class, 5)->states('admin', 'moderator')->create();

Changes

Also, included with this release is a change to the collection only method:

  • Collection::only() now returns all items if $keys is null (#15695)

Bug Fixes:

  • Added workaround for Memcached 3 on PHP7 when using many() (#15739)
  • Fixed bug in Validator::hydrateFiles() when removing the files array (#15663)
  • Fixed model factory bug when $amount is zero (#15764, #15779)
  • Prevent multiple notifications getting sent out when using the Notification facade (#15789)

The full Laravel changelog is available in the GitHub repo.

Filed in:

Eric L. Barnes

Eric is the creator of Laravel News and has been covering Laravel since 2012.

Laravel News Partners