Search code examples
laravellaravel-factory

laravel factories inside nwidart modules


I'm trying to use a laravel factory inside module.

I call factory inside controller like this

$ar_reference = factory(ArReference::class)->create();

This is my factory.

use App\Models\ArReference;
use Faker\Generator as Faker;

$factory->define(ArReference::class, function (Faker $faker) {

    return [
        'reference_no' => 'My Ar'
    ];
});

I call the factory like this inside my module ServiceProvider ArServiceProvider inside registerFactories() function like this.

public function registerFactories() {

        $this->app->singleton(Factory::class, function () {
            return Factory::construct(__DIR__ . '/Database/factories');
        });
}

But unfortunately I'm getting this error

Argument 1 passed to Illuminate\Database\Eloquent\Factory::construct() must be an instance of Faker\Generator, string given, called in /var/www/Modules/Ar/Providers/ArServiceProvider.php on line 94


Solution

  • You need to pass Faker generator in the first argument, see: https://laravel.com/api/5.5/Illuminate/Database/Eloquent/Factory.html#method_construct

    return Factory::construct(\Faker\Factory::create(), __DIR__ . '/Database/factories');