Laravel 8 Database Factories

1.1k views Asked by At

I want to get the override attributes in factory which are defined in seeder at the time of using factories.

For example, in Laravel 7 it was possible to get them as the third parameter

$factory->define(Menu::class, function (Faker $faker, $params) {
      /* here params have the override attributes, which can be used to specify other attributes based on it's value, for example menu_type */
}

Now when upgrading to laravel 8, is there anyway to get those attributes in definition method?

Any ideas would be helpful. Thanks!

3

There are 3 answers

0
Manan On
class ArticleFactory extends Factory {
    /**
     * The name of the factory's corresponding model.
     *
     * @var string
     */
    protected $model = Article::class;

    /**
     * Define the model's default state.
     *
     * @return array
     */
    //
    public function definition() {
        return [
            'user_id' => function(){
                return User::factory()->create()->id;
            },
            'title' => $this->faker->title,
            'body' => $this->faker->sentence,
        ];
    }
}
0
Daniel Loureiro On

This feature has been lost in Laravel 8, but you can still achieve the same results with either afterMaking() or a custom state:

class MenuFactory extends Factory {
  public function configure()
  {
    return $this->afterMaking(function (Menu $menu) {
      /* Here `$menu` has the override attributes, 
         which can be used to specify other attributes based on its value, 
         for example `menu_type` */
    });
  }
}
0
Tyteck On

In facts it is working the same way than before.

class MenuFactory extends Factory {
    /**
     * The name of the factory's corresponding model.
     *
     * @var string
     */
    protected $model = Menu::class;

    public function definition() {
        return [
            'name' => $attributes['name'] ?? $this->faker->name,
            'available' => $attributes['available'] ?? false,
        ];
    }
}

tinker

App\Models\Menu::factory()->make(['name' => 'lorem'])
=> App\Models\Menu {#3346
     name: "lorem",
     available: true,
   }

App\Models\Menu::factory()->make()
=> App\Models\Menu {#3346
     name: "Prof. Theodora Kerluke",
     available: true,
   }

Have a nice day