Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.1 Localize Factory Seeder

I implemented a new factory to generate random data. But I want to have this random data in the format of de_DE. So usually I create a faker object first, but this is not the case in Laravel 5.1 with the new ModelFactory class. How do I localize this then?

$factory->define(App\Models\AED::class, function($faker) {
    return [
        'owner' => $faker->company,
        'street' => $faker->streetAddress,
        'latitude' => $faker->latitude,
        'longitude' => $faker->longitude
    ];
});
like image 653
sesc360 Avatar asked Jun 10 '15 16:06

sesc360


People also ask

How do I run a specific seeder in Laravel?

There are two ways by the help of which we can run a specific seeder file when we need. By using DatabaseSeeder. php file. By using –class flag in artisan command.

How do you call a factory in a seeder?

we need to create create factory class with following command. * The name of the factory's corresponding model. * Define the model's default state. Now we are ready to run seeder.

What is difference between factory and seeder in Laravel?

Database seeder is used to populate tables with data. Model factories is a convenient centralized place to define how your models should be populated with fake data.

What is use Hasfactory in Laravel?

It is a trait that links a Eloquent model to a model factory. Factories are normally used in testing when wanted test-data for a specific model. You can read more about factories in Laravel here: https://laravel.com/docs/9.x/database-testing#model-factories and here: https://laravel.com/docs/9.x/eloquent-factories.


2 Answers

In order to change the default locale used by Faker, the easiest way is to simply override the FakerGenerator binding with your own concrete implementation:

// AppServiceProvider.php
$this->app->singleton(FakerGenerator::class, function () {
    return FakerFactory::create('nl_NL');
});

On top of your AppServiceProvider.php file add the following lines:

use Faker\Generator as FakerGenerator;
use Faker\Factory as FakerFactory;

For example, the above code will mean all Faker instances are created using the nl_NL provider, thus creating Dutch faker data.

Remember: this has to happen after the DatabaseServiceProvider has been executed, so make sure to put your own AppServiceProvider after all of the Laravel ServiceProviders in your config.php array.

like image 114
Max van der Stam Avatar answered Oct 12 '22 05:10

Max van der Stam


Try

$factory->define(App\Models\AED::class, function($faker) {
    $faker->locale = "YOUR_LOCALE";
    ...
});
like image 34
chanafdo Avatar answered Oct 12 '22 04:10

chanafdo