'How to fix Call to undefined method App\Models\TableName::factory?

I have created a seeder that populates data in Laravel but was having a BadMethodCallException Call to undefined method App\Models\Project::factory(). Why is this happening? Below is my seeder code.

<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use App\Models\{
    Project, User
};

class ProjectSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        Project::factory()->count(10)->create();

        foreach(Project::all() as $project) {
            $users = User::inRandomOrder()->take(rand(1, 3))->pluck('id');
            $project->users()->attach($users);
        }
    }
}


Solution 1:[1]

First check the project factory class inside path

database/factories/ProjectFactory.php

If it not exist create it

<?php

namespace Database\Factories;

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

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

    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {

   //add your custom seeder data 
        return [
            "project_tittle" => $this->faker->catchPhrase,
            "client_name" => $this->faker->name(),
            "days" => rand(45, 60),
            "description" => $this->faker->text,
            "start_date" => $this->faker->date('Y-m-d'),
            "end_date" => $this->faker->date('Y-m-d'),
            "current_status" => 1,
            "completion_percentage" => 0
        ];
    }
} 

If your are using different namespace on model you need to add model like this in your factoryclass

protected $model = Project::class;

I hope it works for you

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Saravana Sai