Faker is a PHP library that generates fake data for you

how to get city inside a especific country with Faker extension

i'm working with fzaninotto/Faker extension in Laravel 5 to populate my database, the thing is that I have a table countries and a table Cities so, I call $faker->country but how can I get a city that is inside that country? I don't want for example that Bogotá belongs to EEUU Thank you!

Source: (StackOverflow)

Testing a laravel controller - Faking a Illuminate\Http\Request

I have a controller which is getting an instance of Illuminate\Http\Request injected through the constructor. Now I need to write an unit test that test a call in the controller which uses the values from the Request instance. I have decided to use Faker. How to use Faker to generate an associative array so that I can use the array in my test case like,


And the dynamic array will automatically be available in my controllers request.

Source: (StackOverflow)

SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect datetime value: '2008-03-30 02:56:12'

System Local PHP 5.6.19 App made with Laravel 5.0, using fzaninotto/Faker as seeder Mysql remote

Remote MySQL Debian 8 with MariaDB 10.1.13-MariaDB-1~jessie

Running seeder

php artisan migrate:reset; php artisan migrate; php artisan db:seed

After seeder add an indeterminate number of users (different each time the reproduction of the error) get error:

  SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect datetime value: '2008-03-30 02:56:12' for column 'created_at' at row 1 (S
  QL: insert into `users` (`type`, `name`, `email`, `nick`, `password`, `vat`, `address`, `zipcode`, `city`, `state`, `country`, `cr
  eated_at`, `updated_at`) values (customer, Adrian Santos, qpuig@live.com, rzavala12, y$Veqd2mkgRHtl6VKtYBV0yey77tVLo34.6THXqhtGRwg
  /Ea73/FhlK, 02058805Y, Plaça Abril, 85, 96º D, 44824, Vargas de San Pedro, 57431, San Roig, Huesca, ES, 2008-03-30 02:56:12, 2008-
  03-30 02:56:12))

Well.. date time it's 2008-03-30 02:56:12

A example of latest 3 users created with the seeder before get error:

INSERT INTO `users` (`id`,`type`,`email`,`nick`,`password`,`name`,`vat`,`address`,`zipcode`,`city`,`state`,`country`,`totals`,`remember_token`,`created_at`,`updated_at`) VALUES (15053,'buyer','asauceda@live.com','celia657','$2y$10$P4SOJOAQHsC8W7ctJ5v1F.8loccYzjAW95ILwWZ1RzObNs01hKjr2','Bruno Aguado','71514876X','Paseo Corral, 1, Entre suelo 0º, 63362, La Saiz','58061','Navarrete de Ulla','Cádiz','ES',NULL,NULL,'2012-09-13 06:01:51','2012-09-13 06:01:51');
INSERT INTO `users` (`id`,`type`,`email`,`nick`,`password`,`name`,`vat`,`address`,`zipcode`,`city`,`state`,`country`,`totals`,`remember_token`,`created_at`,`updated_at`) VALUES (15052,'buyer','ana.serna@live.com','cristian126','$2y$10$fe2Hdh4p0bttNfo9uzwSe.L5OOzPwsm5p8g5.YhW5PAoxKcSObDta','Enrique Rivero','06604287K','Ronda Saul, 321, 8º C, 76264, San Álvarez de Arriba','11402','El Roybal Baja','Zamora','ES',NULL,NULL,'2007-11-14 16:39:41','2007-11-14 16:39:41');
INSERT INTO `users` (`id`,`type`,`email`,`nick`,`password`,`name`,`vat`,`address`,`zipcode`,`city`,`state`,`country`,`totals`,`remember_token`,`created_at`,`updated_at`) VALUES (15051,'buyer','iluna@terra.com','aalmanza21','$2y$10$EA.NhWHuT8.nGoZjD18hqOKatHH3MbboY2DjZywlceH8K60spAe5m','Miriam Riojas','24055470T','Calle Soriano, 0, 75º A, 29744, L\' Montenegro','12236','As Martínez','Illes Balears','ES',NULL,NULL,'2013-03-25 23:15:50','2013-03-25 23:15:50');
INSERT INTO `users` (`id`,`type`,`email`,`nick`,`password`,`name`,`vat`,`address`,`zipcode`,`city`,`state`,`country`,`totals`,`remember_token`,`created_at`,`updated_at`) VALUES (15050,'buyer','qsalgado@hotmail.com','mateo26','$2y$10$6.lFRsqEjXb1kdZOhAX7Cu1Xecgu1ZvAkhaADKcfSpEi6ODQM9nRK','Alonso Núñez','50161945A','Camino Ainara, 78, 65º A, 17155, L\' Ayala del Pozo','47226','Román de las Torres','Las Palmas','ES',NULL,NULL,'2016-05-12 11:00:01','2016-05-12 11:00:01');

Read some information, such MYSQL incorrect DATETIME format, How to make sql-mode=“NO_ENGINE_SUBSTITUTION” permanent in MySQL my.cnf and verify mysql variables for this question.

MariaDB [(none)]> select @@GLOBAL.sql_mode;
select @@GLOBAL.sql_mode

| @@GLOBAL.sql_mode      |
MariaDB [(none)]> select @@SESSION.sql_mode;
select @@SESSION.sql_mode

| @@SESSION.sql_mode     |
1 row in set (0.00 sec)

Source: (StackOverflow)

Using faker with selenium and python

I have installed faker:

pip install faker

import unittest
from selenium import webdriver
from selenium import selenium
from faker import Faker

f = Faker()

Then I have a class:

class Test(unittest.TestCase):
     name_field = self.browser.find_element_by_name('input_1')

The driver adds the name f.name() in the input box instead of a random name

What am I doing wrong?

Source: (StackOverflow)

Getting started with Faker.js with Meteorite

I am trying to user Faker.js with Meteorite. I have added this package:


I am trying to add fake users on server startup:

Meteor.startup(function () {
    // code to run on server at startup

    // add 100 fake tips and 10 fake articles and 50 fake users
    for (var i=0; i<50; i++) {
        // Accounts.createUser(Faker.Internet.userName(), Faker.Internet.email(), "1234");


but I get an error:

ReferenceError: Faker is not defined

Not sure how to fix this...

Source: (StackOverflow)

MySQL data being lost after getting inserted successfully with Python mysql.connector

I'm using python mysql.connector for some database operation. My database table structure is like this:

enter image description here

I running a python script with Faker Package(fake-factory 0.5.0) to populate this database table. After insertion I run a query to verify that data is properly stored into the table. The python script shows all inserted data and finishes with exit code 0

But when I explore that table through phpMyadmin it doesn't show those inserted rows. These inserted data doesn't persist in after the next run yet.

Here is my code:

import mysql.connector
from faker import Faker

fake = Faker()

cnx = mysql.connector.connect(user='root', password='001',
cursor = cnx.cursor()

for i in range(1, 5):
    query = "insert into user " + "(userid, name) values("+ str(i) + ", '" + fake.name() + "')"

query = "select * from user"

for (x) in cursor:
    print ("name = " + format(x))


Source: (StackOverflow)

Error when trying to import data with Marak/faker.js

I can't seem to find my problem. Anyone see what I am doing wrong? This project is made with Meteor and React.

My import file:

import _ from 'lodash';
import { lorem, faker } from 'faker';
import { Comments } from '../../api/comments/comments';
import { insertComment } from '../../api/comments/methods.js';
import { Bert } from 'meteor/themeteorchef:bert';

Meteor.startup(() => {
	// Great place to generate some data

	// Check to see if data excists in the collection
	// See if the collection has any records
	const numberRecords = Comments.find({}).count();
	if (!numberRecords) {
		// Generate some data...
		_.times(100, () => {
			const title = faker.lorem.title();
			const content = faker.lorem.title();

				title, content,
			}, (error) => {
				if (error) {
			        Bert.alert(error.reason, 'danger');
			    } else {
			        target.value = '';
			        Bert.alert('Comment added!', 'success');

And this is the method file I use to write the comment:

import { Comments } from './comments';
import { SimpleSchema } from 'meteor/aldeed:simple-schema';
import { ValidatedMethod } from 'meteor/mdg:validated-method';
import { rateLimit } from '../../modules/rate-limit.js';

export const insertComment = new ValidatedMethod({
  name: 'comments.insert',
  validate: new SimpleSchema({
    title: { type: String },
    content: { type: String },
  run(comment) {

  methods: [

  limit: 5,
  timeRange: 1000,

This is the error code I am getting in my terminal: TypeError: Cannot read property 'lorem' of undefined.

Any help is highly appreciated.


As suggested I made the changes to the import from "import { lorem, faker } from 'faker';" to "import faker from 'faker';"

I also changed this "faker.lorem.title();" to "faker.hacker.noun();"

Thanks Guig!

Source: (StackOverflow)

Testing data generator for Intersystems Caché?

Are there any easy ways (i.e. libraries) to create testing data for Caché, similar to the Populator and Faker gems for Ruby/Rails?

** edit ** I am trying to create test data for an Epic implementation. In addition to the electronic-medical-record (EMR) application, the implementation includes a tool called 'Text'. I'm hoping that I can use the data-generator with Text.

Source: (StackOverflow)

Close Couchbase connection once entries have been saved

I use Faker to insert some dummy data into Couchbase database. It seems to me that I need to close the connection on the insertion operations complete because now when it inserts all the entries, the app keeps being active, doesn't return me to console. How to manage it?

Source: (StackOverflow)

In Rails when using the Faker gem, Im unable to generate unique data. How to fix it?

When I run db:populate, it gives the following error :

Validation failed: Email has already been taken, Nyaaid has already been taken

The email should be unique and the ID should be unique! Here's the validation for the nyaaid :

validates :nyaaid, format: { with: VALID_NYAAID_REGEX }, uniqueness: { case_sensitive: false }

Here's the Faker code, sample_data.rake :

namespace :db do
  desc "Fill database with sample data"
  task populate: :environment do
    Awardunit.create!(nyaaid: "NYAA/N/WP0001", name: "Test Unit", address: "No. 50, Kalpitiya Road, Maradana", district: "Colombo", contact: ["23232223"], email: "abc@localhost.com", insthead: "Namal Kaluaarachchi", instheadcontact: ["324234234"], datestarted: "1/10/2013", allowedmem: "5", remarks: "")

    @districts = ['Ampara', 'Anuradhapura', 'Badulla', 'Batticaloa', 'Colombo', 'Galle', 'Gampaha', 'Hambantota', 'Jaffna', 'Kalutara', 'Kandy', 'Kegalle', 'Kilinochchi', 'Kurunegala', 'Mannar', 'Matale', 'Matara', 'Moneragala', 'Mullaitivu', 'Nuwara Eliya', 'Polonnaruwa', 'Puttalama', 'Ratnapura', 'Trincomalee', 'Vavuniya']
    @allowedmem = Array(5..20)

    @from = 10.years.ago
    @to = Time.now

    def rand_date
      Time.at(@from + rand * (@to.to_f - @from.to_f)).strftime("%d/%m/%Y")

    @idarray = Array(2222..9999)

    def pickidarray
      id = @idarray.sample
      return id

    50.times do |n|
      nyaaid = "NYAA/N/WP#{pickidarray}"
      name  = Faker::Company.name
      address = Faker::Address.street_address
      district = @districts.sample
      contact = Faker::PhoneNumber.phone_number
      email = "example-#{n+1}@slnyaa.org"
      insthead = Faker::Name.name
      instheadcontact = Faker::PhoneNumber.phone_number
      datestarted = rand_date
      allowedmem = @allowedmem.sample
      remarks = Faker::Lorem.paragraphs(rand(1..2))
      Awardunit.create!(nyaaid: nyaaid, name: name, address: address, district: district, contact: contact, email: email, insthead: insthead, instheadcontact: instheadcontact, datestarted: datestarted, allowedmem: allowedmem, remarks: remarks)

Source: (StackOverflow)

Should we be using Faker in Rails Factories?

I love Faker, I use it in my seeds.rb all the time to populate my dev environment with real-ish looking data.

I've also just started using Factory Girl which also saves a lot of time - but when i sleuth around the web for code examples I don't see much evidence of people combining the two.

Q. Is there a good reason why people don't use faker in a factory?

My feeling is that by doing so I'd increase the robustness of my tests by seeding random - but predictable - data each time, which hopefully would increase the chances of a bug popping up.

But perhaps that's incorrect and there is either no benefit over hard coding a factory or I'm not seeing a potential pitfall. Is there a good reason why these two gems should or shouldn't be combined?

Source: (StackOverflow)

Issue with Faker gem

I installed Fabrication and Faker in my Rails 4 project

I created a fabrarication object:

Fabricator(:course) do
  title { Faker::Lorem.words(5) }
  description { Faker::Lorem.paragraph(2) } 

And I'm calling the Faker object within my courses_controller_spec.rb test:

require 'spec_helper'

describe CoursesController do
  describe "GET #show" do
    it "set @course" do
      course = Fabricate(:course)
      get :show, id: course.id
      expect(assigns(:course)).to eq(course)
    it "renders the show template"

But for some reason, the test failes at line 6:

course = Fabricate(:course)

the error message is:

Failure/Error: course = Fabricate(:course)
   can't cast Array to string

Don't know exactly why this is failing. Has anyone experienced the same error message with Faker?

Source: (StackOverflow)

Use Faker gem to generate correlated city, postal code, country code values

Is there a way to get the Faker gem to generate 'correlated' city and country code values?

For example,

  • Vancouver, CA
  • Minneapolis, MN

I'm doing this:

FactoryGirl.define do
  factory :location do
    city {Faker::Address.city}
    country_code {['US', 'CA'].sample}

But there is no guarantee that the city will actual reside in country_code.

I'd settle for something like:

postal_code {Faker::Address.postcode(['US', 'CA'].sample) }

Which I could then geocode to get the other values.

Source: (StackOverflow)

How to get future date in Faker

How do I get future dates with:


dateTime($max = 'now')  

i.e. what should the $max value be for datetime in the future

Source: (StackOverflow)

How to seed database in yii2?

I am new to Yii framework. I want to seed my database like it can be done in Laravel framework using Faker. I tried this http://www.yiiframework.com/forum/index.php/topic/59655-how-to-seed-yii2-database/ but it does not provide much details. I would really appreciate if someone can help me out with the steps in details.

Source: (StackOverflow)