Home > OS >  Model factory is not found
Model factory is not found

Time:10-16

So I'm trying to seed my ProductsFactory, but I got this issue:

 Class "Database\Factories\ProductFactory" not found

Here's my code

ProductFactory

<?php

namespace Database\Factories;

use App\Models\Model;
use Illuminate\Database\Eloquent\Factories\Factory;

class ProductsFactory extends Factory
{
    protected $model = Model::class;
    public function definition()
    {
        return [
            'name' => $this->$faker->name(),
            'price' => $this->$faker->randomFloat(2, 0, 8),
            'description' => $this->$faker->text()
        ];
    }
}
?>

ProductSeeder

<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;

class ProductSeeder extends Seeder
{
    public function run()
    {
        \App\Models\Product::factory(10)->create();
    }
}

Product

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    use HasFactory;
}

I'm using the Laravel 8.x and the Mysql for the DB Please, someone can help me? It's for a project to my class

CodePudding user response:

in your factory class, you should declare the variable $model correctly to point to the destination model, in this case, Product model:

class ProductsFactory extends Factory
{
    protected $model = Product::class;

however, if the problem stays, you can connect the model and the factory.

in your Product model:

protected static function newFactory()
{
    return ProductFactory::new();
}

CodePudding user response:

The error says: Class "Database\Factories\ProductFactory" not found, meaning that Laravel looks for a class called ProductFactory. Your class however is called ProductsFactory.

Rename the class (and probably the filename) and it should work.

  • Related