Unable to use Laravel Factory in Tinker

Lizesh Shakya picture Lizesh Shakya · Sep 10, 2020 · Viewed 7.1k times · Source

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

Answer

N'Bayramberdiyev picture N'Bayramberdiyev · Sep 12, 2020

In Laravel 8.x release notes:

Eloquent model factories have been entirely re-written as class based factories and improved to have first-class relationship support.

Global factory() function is removed as of Laravel 8. Instead, you should now use model factory classes.

  1. Create a factory:
php artisan make:factory ItemFactory --model=Item
  1. Make sure that Illuminate\Database\Eloquent\Factories\HasFactory trait is imported in your model:
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Item extends Model
{
    use HasFactory;

    // ...
}
  1. Use it like this:
$item = Item::factory()->make(); // Create a single App\Models\Item instance

// or

$items = Item::factory()->count(3)->make(); // Create three App\Models\Item instances

Use create method to persist them to the database:

$item = Item::factory()->create(); // Create a single App\Models\Item instance and persist to the database

// or

$items = Item::factory()->count(3)->create(); // Create three App\Models\Item instances and persist to the database

Being said that, if you still want to provide support for the previous generation of model factories within Laravel 8.x, you can use laravel/legacy-factories package.