Skip to content
Advertisement

Unable to use Laravel Factory in Tinker

I am unable Model Factory in Laravel Tinker.

//ItemFactory.php

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

    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
        return [
            'name' => $this->faker->name,
            'slug' => $this->faker->slug(5, true),
            'code' => $this->faker->words(5, true),
            'description' => $this->faker->sentence,
            'price' => $this->faker->randomNumber(1000, 10000),
            'size' => $this->faker->randomElement(['Small', 'Medium', 'Large',]),
        ];
    }
}

Inside Tinker

>>> factory(AppItem::class)->create();

It throws me an error:

PHP Fatal error: Call to undefined function factory() in Psy Shell code on line 1

Advertisement

Answer

After going through the documentation of Model Factory, there were major changes in Laravel 8 version.

For using Model Factory anywhere inside Laravel 8:

  1. Inside Model, we need to import the IlluminateDatabaseEloquentFactoriesHasFactory trait

  2. New command to implement the factory

AppItem::factory()->create();
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement