quelvinmp's avatar

Does Factory only work if my project assumes the specific architecture it expects or can I configure it the way I want?

I'm creating seeders for my models and I chose to use factories to be able to add several records without much effort.

But I found a problem! It seems that the Factory class expects my project's architecture to be App/Models and so all my tables are there, but the project I'm currently working on is all structured differently... The models are each in one place separate. I would have to find a more dynamic way to make Factory access each model... Does anyone have any idea what to do?

Ex.: a model is in App/Modules/Contents/Models

Below is the Factory class method that returns the model path:

public function modelName()
    {
        $resolver = static::$modelNameResolver ?: function (self $factory) {
            $namespacedFactoryBasename = Str::replaceLast(
                'Factory', '', Str::replaceFirst(static::$namespace, '', get_class($factory))
            );

            $factoryBasename = Str::replaceLast('Factory', '', class_basename($factory));

            $appNamespace = static::appNamespace();

            return class_exists($appNamespace.'Models\'.$namespacedFactoryBasename)
                        ? $appNamespace.'Models\'.$namespacedFactoryBasename
                        : $appNamespace.$factoryBasename;
        };

        return $this->model ?: $resolver($this);
    }
0 likes
4 replies
Tray2's avatar
Tray2
Best Answer
Level 74

If your model isn't where it usually is, you need to update the namespace and then import the model class into your factory.

namespace Database\Factories;

use App\Models\Actor; //The namespace for the model
use Illuminate\Database\Eloquent\Factories\Factory;

class ActorFactory extends Factory
{
    protected $model = Actor::class; //Model used.

    public function definition(): array
    {
        return [
            'first_name' => $this->faker->firstName(),
            'last_name' => $this->faker->lastName(),
        ];
    }
}
1 like
quelvinmp's avatar

@Tray2

It worked! Thank you very much.

Strange things, I didn't find this information in my research... It was so simple! LOL

Thanks again. Have a great week!

quelvinmp's avatar

It was in the documentation this whole time lol

Please or to participate in this conversation.