Laravel advanced database seeding

But there is more!Seed your database with a relationAfter we created the seeder for our users table we also want to seed our phones table and connect each phone with a random user.

Of course we can pick a random number between 1 and 1,000 and use that as the user_id, but what if we work with real users and (for some reason) user ID’s 6, 140 and 578 are deleted.

Using this ID’s can create an issue in our software.

Lets see how we can avoid this and connect a phone with a real user.

<?phpuse IlluminateDatabaseSeeder;class PhonesTableSeeder extends Seeder{ /** * Run the database seeds.

* * @return void */ public function run() { # Lets create 150 random phones $phones = factory(AppPhone::class, 150)->create([ 'user_id' => $this->getRandomUserId() ]); } private function getRandomUserId() { $user = AppUser::inRandomOrder()->first(); return $user->id; }}In the example above I use a factory to generate 150 phones.

In the create function you can overwrite any value from the factory for each record created in the database.

In this example I overwrite the user_id that is defined in the factory and collect 1 random ID from the users table.

Pretty simple but highly effective.

Use default values and null valuesIn every database design there are mandatory fields and fields which are not mandatory.

It is a common mistake that in migrations and seeders all fields are populated with the right data.

Populating all fields always with a value can cause problems in your software when using it in real life.

When I create a seeder for a field that not mandatory I usually use the array_random function to seed the column either with a (faker) value or a null value.

An example is shown below;<?phpuse FakerGenerator as Faker;$factory->define(AppCompany::class, function (Faker $faker) { return [ 'name' => $faker->company, 'headquarter' => array_random([$faker->city, null]), 'no_employees' => array_random([rand(1, 250), null]), 'cover_letter' => array_random([$faker->realText(350), null]) ];});In the example above the company name is mandatory.

The other columns are not so I used the ‘nullable()’ function in the migration.

Using the array_random function gives me the ability to seed the database with null values … sometimes.

After reading all this I hope everybody is convinced about the added value of migrations and seeders.

If you are not convinced yet, there is 1 really good additional reason: You can use these migrations and seeders in your tests which prevents you from repeating yourself.

I hope this information helps you to write better migrations and if you have any question or comments to improve this article then please share it with me ;).. More details

Leave a Reply