vinkla.com

Generate Fake Localized Data with Laravel

Instead of populating the database by yourself, Laravel integrates the Faker package which is used to generate fake English data into your database. What if you want to generate data in your own language?

When testing, it is common to need to insert a few records into your database before executing your test. In version 5.1 Laravel introduced model factories to easily generate fake data into your applications.

If you want to specify a custom locale, you can create a new service provider and overwrite the default locale. In my case, I want the data in Swedish. You can find a full list of locales here.

<?php

/*
 * This file is part of the faker article.
 *
 * (c) Vincent Klaiber <[email protected]>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace App\Providers;

use Faker\Factory;
use Faker\Generator;
use Illuminate\Support\ServiceProvider;

/**
 * This is the faker service provider class.
 *
 * @author Vincent Klaiber <[email protected]>
 */
class FakerServiceProvider extends ServiceProvider
{
    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->registerFaker();
    }

    /**
     * Register the faker generator class.
     *
     * @return void
     */
    protected function registerFaker()
    {
        $this->app->singleton(Generator::class, function () {
            return Factory::create('sv_SE');
        });
    }
}

Once the service provider is created. Add the service provider to the providers array in config/app.php.

App\Providers\FakerServiceProvider::class

That’s it, you are now ready to generate fake data in any language you want!


Like this article? Reach out to me and say hi on Twitter! :wave:
All articles written with ♥ by Vincent Klaiber