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.


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:

  '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