Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 8, Model factory class not found

Tags:

php

laravel

so when using the new model factories class introduced in laravel 8.x, ive this weird issue saying that laravel cannot find the factory that corresponds to the model. i get this error

PHP Error:  Class 'Database/Factories/BusinessUserFactory' not found in .....

tho ive followed the laravel docs, ive no idea whats going on

Here is the BusinessUser class

<?php

namespace App;

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

class BusinessUser extends Model
{
    use HasFactory;
}

and the factory

<?php

namespace Database\Factories;

use App\BusinessUser;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;

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

    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
        return [
            'name' => "dsfsf"
        ];
    }
}


any ideas or leads is greatly appreciated.

like image 816
Ahmed Khattab Avatar asked Sep 17 '20 17:09

Ahmed Khattab


2 Answers

If you upgraded to 8 from a previous version you are probably missing the autoload directive for the Database\Factories namespace in composer.json:

"autoload": {
    "psr-4": {
        "App\\": "app/",
        "Database\\Factories\\": "database/factories/",
        "Database\\Seeders\\": "database/seeders/"
    }
},

You can also remove the classmap part, since it is no longer needed.

Run composer dump after making these changes.

Laravel 8.x Docs - Upgrade Guide - Database - Seeder and Factory Namespace

like image 134
lagbox Avatar answered Nov 02 '22 06:11

lagbox


Apparently you have to respect the folder structure as well. For example, if you have the User Model in the following path: app\Models\Users\User, then the respective factory should be located in database\factories\Users\UserFactory.

like image 16
Abouhassane Abdelhamid Avatar answered Nov 02 '22 06:11

Abouhassane Abdelhamid