Seeding a DB for testing purposes with Laravel and cross-references

  • Create a custom factory to fill up the data correctly
  • Call the factory with the right parameters depending on the status from the seeder
  • Fix the problems that are going to show up because of data structure.

Laravel is going to load all the files under database/factories folder.
We can create a new file there and call it WhateverWeNeedFactory.
 

$factory->state(
  App\Models\Customer::class,
  'gift_card_test',
  function(Faker\Generator$faker){
  $firstName=$faker->firstName;
  $lastName=$faker->lastName;
    return[
      "firstname"=>$firstName,
      "middlename"=>null,
      "surname"=>$lastName,
      "email"=>'m.test@test.com',
      "phone_number"=>'+123456789',
      "dob"=>null,
      "order_count"=>0,
      "total_spent"=>0,
      "created_at"=>Carbon::now(),
      "updated_at"=>Carbon::now(),
      "name"=>$firstName."".$lastName
    ];
  }
);

We are using a factory state which allows the factory to have any parameters changed. Also, the state can be named and called back in case there is a conflict.
 

$factory->state(App\Sample::class, 'named_factory' , function ($faker) {
  return [
  'sample_field' => 'sample'
  ]
});


 
Then in the seeder we can:
 

factory(App\Sample::class)->states('named_factory')->create([
  'sample_field' => 'overwritten value from factory default'
]);


 
If we need a key of the parameter we can do:
 

$sample = Factory(App\Sample::class)->states('named_factory')->create([
  'sample_field' => 'overwritten value from factory default'
]);


 
And then $sample will be available for other seedings, where we can use, for example, ids.

Last bit: to run the seeder from the command line we just have to run:

php artisan db:seed --class=AnyThingWeCalledThatFactory