Search code examples
phpinstancelaravel-5factories

Change factories path in Laravel 5.2


I'm trying to change my factories directory to a custom path, so I'm using this as I saw in a laracasts thread:

use Illuminate\Database\Eloquent\Factory as Factory;

class FactoryServiceProvider extends ServiceProvider
{
    public function register()
    {
            $this->app->singleton(Factory::class, function () {
                return Factory::construct(new Faker\Generator, app_path() .'/Core/Database/Factories');
            });
    }
}

The new path works, my factory files inside the new directory are loaded. But now when I try to use the factory from seeders on php artisan migrate:refresh --seed I'm getting

[InvalidArgumentException] Unknown formatter "name"

from the $faker instance inside the factory definition:

$factory->define(User::class, function (Faker\Generator $faker) {
    return[
        'name' => $faker->name,
        'email' => $faker->freeEmail,
        'password' => bcrypt($faker->word),
        'remember_token' => str_random(10)
    ];
});

This error appears with all the formatters, not just with name.

Where is the problem? The factory works fine before I change the path.


Solution

  • I couldn't find answer for a while, so maybe this will help someone.

    In your service provider, load additional path to your factories. This way Laravel not only looks for factories in default folder, but also in custom folder.

    use Illuminate\Database\Eloquent\Factory;
    ...
      public function boot() {
        $this->registerEloquentFactoriesFrom(__DIR__ . '/../Database/Factories');
    }
    
    
    protected function registerEloquentFactoriesFrom($path) {
        $this->app->make(Factory::class)->load($path);
    }
    

    __DIR__ is path to to the directory you have your provider in. My directory structure looks like this.

    src
     |    
     +-- Providers
     |  |  
     |  +-- CustomServiceProvider.php
     |    
     +-- Database
     |  |  
     |  +-- Factories
    

    Of course different approach will also work for it.

    Found on https://github.com/caffeinated/modules/issues/337