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.
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
Okay, finally I found how to make it work:
<?php
use Faker\Generator as FakerGenerator;
use Illuminate\Database\Eloquent\Factory as EloquentFactory;
use Illuminate\Support\ServiceProvider;
class FactoryServiceProvider extends ServiceProvider
{
public function register()
{
$this->app->singleton(EloquentFactory::class, function ($app){
$faker = $app->make(FakerGenerator::class);
$factories_path = 'Your/Custom/Path/To/Factories';
return EloquentFactory::construct($faker, $factories_path);
});
}
}
The app->make
does the trick:
$app->make(FakerGenerator::class)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With