Search code examples
phplaraveltinkerlaravel-8

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(App\Item::class)->create();

It throws me an error:

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


Solution

  • 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 Illuminate\Database\Eloquent\Factories\HasFactory trait

    2. New command to implement the factory

    App\Item::factory()->create();