Jonnny
Jonnny

Reputation: 5039

Populate tables with Faker

I'm struggling to work out how to use Faker with Yii2. Everything seems to be through the console, can it not be used in the web app? I'd like to see the data generated on screen and then work to insert this data into the DB once I've perfected it. I have a lot of foreign keys that I want to make sure are related properly. For instance, making sure a certain city FK has the right corresponding state FK.

I've been through and looked at the testing part on the docs and loads of google links, but this doesn't seem to be what I really need. Maybe I'm wrong? I was hoping to do something like this : https://www.youtube.com/watch?v=sSDh1zfz-5s

Any help at appreciated :-)

Upvotes: 3

Views: 397

Answers (1)

Joe Miller
Joe Miller

Reputation: 3893

If you want to use Faker as a web app, you can use the FakerController in Yii, as it is only set up to use as a console app.

To use it in a web app, simply set up your controller like this.

<?php

namespace frontend\controllers;

use Yii;
use Faker;
use yii\web\Controller;
class SiteController extends Controller {
    public function actionIndex() {
        $faker = \Faker\Factory::create();
        $titles = $faker->name(20);
        return $this->render('index', ['titles' => $titles]);
    }
}

It's then up to you to create the code to insert the data into your database, much like the guy did in the video.

By the way, I had no idea Faker existed, this will save me so much time in my projects! Thanks!

Upvotes: 2

Related Questions