Laravel 8 factory class is not overriding the parameters while creating the factories

1.8k Views Asked by At

I am developing a web application using Laravel 8. I have noticed that quite a lot of things have changed in Laravel 8 including factories.

I have a factory class MenuCategoryFactory for my MenuCategory model class with the following definition.

<?php

namespace Database\Factories;

use App\Models\Menu;
use App\Models\MenuCategory;
use Illuminate\Database\Eloquent\Factories\Factory;

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

    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
        return [
            'name' => $this->faker->name,
            'menu_id' => Menu::factory()->create(),
        ];
    }
}

In my code (database seeder class), I am trying to override the menu_id as follow while I am creating the factories.

$restaurant = Restaurant::first();
        MenuCategory::factory()->create([
            'menu_id' => $restaurant->menu->id
        ]);

But it is not using the value I passed, $restaurant->menu->id. Instead, it is creating a new menu. What is wrong missing in my code and how can I fix it?

2

There are 2 best solutions below

0
On

Change the definition to

public function definition()
    {
        return [
            'name' => $this->faker->name,
            'menu_id' => function() {
                 Menu::factory()->create()->id,
            }
        ];
    }

then you can replace the value

0
On

In your factory definition, don't call ->create(), instead set it up like this:

public function definition()
    {
        return [
            'name' => $this->faker->name,
            'menu_id' => Menu::factory(),
        ];
    }

Then you you should be able to set up related models (assuming you the relationships setup in the model) like this:

$restaurant = Restaurant::first();
MenuCategory::factory()->for($restaurant)->create();