How to declare $faker in the seed file in Laravel when overriding for argument to factory?
Solution 1
Use Faker\Factory::create() to create and initialize a faker generator, which can generate data by accessing properties named after the type of data you want.
$faker = Faker\Factory::create();
And should work just fine. source.
Solution 2
It's always a good idea to keep things consistent, so I would suggest doing it the same way as the Factory class does it. Your seeder would then look like this:
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
use Faker\Generator;
use Illuminate\Container\Container;
class MySeeder extends Seeder
{
/**
* The current Faker instance.
*
* @var \Faker\Generator
*/
protected $faker;
/**
* Create a new seeder instance.
*
* @return void
*/
public function __construct()
{
$this->faker = $this->withFaker();
}
/**
* Get a new Faker instance.
*
* @return \Faker\Generator
*/
protected function withFaker()
{
return Container::getInstance()->make(Generator::class);
}
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
// ...
}
}
Solution 3
...
use Faker\Factory as Faker;
...
class DatabaseSeeder extends Seeder
{
public function run()
{
$this->faker = Faker::create();
$number = $this->faker->randomDigit();
}
}
Solution 4
I am using this in Laravel 9.x.
// database/seeders/DatabaseSeeder.php
namespace Database\Seeders;
use Faker\Generator;
class DatabaseSeeder extends Seeder
{
public function run()
{
$faker = app(Generator::class);
// use
// $faker->text()
// $faker->dateTimeThisYear()
}
}
Solution 5
I think you need to use it like this
factory('App\Client', 300)->create()->each(function($client) {
$user = App\User::find(rand(3, 10));
//That if you have set a Many to many relationship (which I honestly doubt of it but just showing for the exemple)
$client->users()->attach($user);
//That if you have set a belongsTo relationship
$client->user()->associate($user);
//That if relationship is not set
$client->user_id = $user->id;
}
Lisendra
Updated on June 28, 2022Comments
-
Lisendra almost 2 years
I am trying to create multiple model of seeds like seedt1, seedt2, seedt3 with parameters for the sample.
I am aware of factory states, i don't want to use it,i want to keep my factory model minimal and clean as possible.
i have my model factory:
<?php /** @var \Illuminate\Database\Eloquent\Factory $factory */ use App\User; use App\Client; use App\Query; use App\Task; use Faker\Generator as Faker; ////////// Users factory ////////// $factory->define('App\User', function (Faker $faker) { $faker->locale = 'fr_FR'; return [ 'full_name' => $faker->name, 'email' => $faker->unique()->safeEmail, 'password' => bcrypt('secret'), 'remember_token' => Str::random(10), 'objective' => '0', 'role_id' =>1, 'isActive' => '1', 'img_path' =>'user-lg.jpg', ]; }); ////////// Clients factory ////////// $factory->define('App\Client', function ($faker) { $faker->locale = 'fr_FR'; return [ 'name' => $faker->company, 'legalname' => $faker->name, 'legalname2' => $faker->name, 'legalname3' => $faker->name, 'email' => $faker->email, 'address' => $faker->address, 'country' => $faker->country, 'website' => $faker->domainName, 'telephone' => $faker->phoneNumber, 'telephone2' => $faker->phoneNumber, 'fax' => $faker->PhoneNumber, 'other1' => $faker->email, 'other2' => $faker->email, 'other3' => $faker->email, 'foundeddate' => $faker->dateTimeThisDecade, 'crmregistered' => $faker->dateTimeThisYear, 'comments' => $faker->realText($maxNbChars = 300, $indexSize = 2), 'insurancenumber' => $faker->numberBetween($min = 80000, $max = 150000), 'data1' => $faker->boolean($chanceOfGettingTrue = 50), 'data2' => $faker->boolean($chanceOfGettingTrue = 50), 'type_id' => $faker->numberBetween($min = 1, $max = 2), 'isActive' => '1', 'user_id' => $faker->numberBetween($min = 3, $max = 15), 'img_path' =>'imageUrl($width, $height, \'cats\')', ]; }); ////////// Queries factory ////////// $factory->define('App\Query', function ($faker) { $faker->locale = 'fr_FR'; return [ 'guests_no' => $faker->numberBetween($min = 50, $max = 500), 'days_no' => $faker->numberBetween($min = 3, $max = 7), 'value' => $faker->ean8, 'arrival_date' => $faker->dateTimeInInterval($startDate = '+1 years', $interval = '+ 14 days', $timezone = null), 'departure_date' => $faker->dateTimeInInterval($startDate = '+1 years', $interval = '+ 21 days', $timezone = null), 'file_name' => $faker->numerify('dossier ######'), 'file_number' => $faker->ean8, 'facture_number' => $faker->creditCardNumber, 'guide' => $faker->boolean($chanceOfGettingTrue = 50), 'rentacar' => $faker->boolean($chanceOfGettingTrue = 50), 'aerial' => $faker->boolean($chanceOfGettingTrue = 50), 'user_id' => $faker->numberBetween($min = 3, $max = 15), 'client_id' => $faker->numberBetween($min = 1, $max = 1000), 'transport_type_id' => $faker->numberBetween($min = 1, $max = 3), 'created_at' => $faker->dateTimeThisYear, 'payment_status_id' => $faker->numberBetween($min = 1, $max = 3), 'query_status_id' => $faker->numberBetween($min = 1, $max = 7), 'query_type_id' => $faker->numberBetween($min = 1, $max = 3), 'isActive' => '1', 'notified' => $faker->boolean($chanceOfGettingTrue = 50), ]; }); ////////// Task factory ////////// $factory->define('App\Task', function ($faker) { $faker->locale = 'fr_FR'; return [ 'text' => $faker->realText($maxNbChars = 300, $indexSize = 2), 'name' => $faker->name, 'status' => $faker->ean8, 'user_id' => $faker->numberBetween($min = 3, $max = 15), 'query_id' => $faker->numberBetween($min = 1, $max = 500), 'isActive' => '1', 'query_status_id' => $faker->numberBetween($min = 1, $max = 7), ]; }); ////////// State sample factory ////////// /*$factory->state(App\User::class, 'delinquent', function ($faker) { return [ 'account_status' => 'delinquent', ]; });*/
and my seed file:
<?php use Illuminate\Database\Seeder; class sampleT1 extends Seeder { public function run() { factory('App\User', 1)->create(['role_id' =>'2',]); //1 financial user id 2 factory('App\User', 3)->create(['role_id' =>'4',]); //3 managers id 3-5 factory('App\User', 5)->create(); //10 users id 6-10 factory('App\Client', 300)->create(['user_id' => $faker->numberBetween($min = 3, $max = 10),]); //300 clients factory('App\Query', 1000)->create(['user_id' => $faker->numberBetween($min = 3, $max = 10), 'client_id' => $faker->numberBetween($min = 1, $max = 300),]); //300 queries factory('App\Task', 5000)->create(['user_id' => $faker->numberBetween($min = 3, $max = 10), 'query_id' => $faker->numberBetween($min = 1, $max = 250),]); //5000 tasks //factory('App\User', 50)->states('premium', 'delinquent')->create(); } }
when i run my seed with :
php artisan db:seed --class=sampleT1
i get result:
deployer@debdaddytp:/var/www/mice$ php artisan db:seed --class=sampleT1 ErrorException Undefined variable: faker at database/seeds/sampleT1.php:20
obviously the variable of faker is not inherited from the model factory, how should i declare it in my seed for this to work?
-
Lisendra almost 4 yearsI have added now these to modifications in my seed file like this: pastebin.com/zyymnAAj and i get now this: php artisan db:seed --class=sampleT1 Error Class 'Faker\Generator\Factory' not found at database/seeds/sampleT1.php:6
-
Lisendra almost 4 yearsi am not sure this answer my question, my factory is fine, i am looking to fix my seed file that override data to my factory model
-
r0ulito almost 4 yearsThat a snippet to be put into a seeder. It's
factory()->create()
and not$factory->define()
-
jewishmoses almost 4 yearsRemove: use Faker\Generator as Faker; and it should be fine. I have updated my answer and tested it.
-
Lisendra almost 4 yearsthank you, this is the right answer! have a good day Sir!
-
Florian Falk about 3 yearsThis is the working solution with the "new" faker since the old one is archived
-
Watercayman almost 3 yearsSimple and correct for a problem I couldn't find a solve. Thank you!