Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel - Seeding Relationships

Tags:

php

laravel

In Laravel, database seeding is generally accomplished through Model factories. So you define a blueprint for your Model using Faker data, and say how many instances you need:

$factory->define(App\User::class, function (Faker\Generator $faker) {     return [         'name' => $faker->name,         'email' => $faker->email,         'password' => bcrypt(str_random(10)),         'remember_token' => str_random(10),     ]; });  $user = factory(App\User::class, 50)->create(); 

However, lets say your User model has a hasMany relationship with many other Models, like a Post model for example:

Post:    id    name    body    user_id 

So in this situation, you want to seed your Posts table with actual users that were seeded in your Users table. This doesn't seem to be explicitly discussed, but I did find the following in the Laravel docs:

$users = factory(App\User::class, 3)     ->create()     ->each(function($u) {          $u->posts()->save(factory(App\Post::class)->make());     }); 

So in your User factory, you create X number of Posts for each User you create. However, in a large application where maybe 50 - 75 Models share relationships with the User Model, your User Seeder would essentially end up seeding the entire database with all it's relationships.

My question is: Is this the best way to handle this? The only other thing I can think of is to Seed the Users first (without seeding any relations), and then pull random Users from the DB as needed while you are seeding other Models. However, in cases where they need to be unique, you'd have to keep track of which Users had been used. Also, it seems this would add a lot of extra query-bulk to the seeding process.

like image 522
djt Avatar asked Feb 17 '16 06:02

djt


People also ask

What is seeding in Laravel?

Laravel includes the ability to seed your database with data using seed classes. All seed classes are stored in the database/seeders directory. By default, a DatabaseSeeder class is defined for you. From this class, you may use the call method to run other seed classes, allowing you to control the seeding order.

What is the difference between seeder and factory in Laravel?

Database seeder is used to populate tables with data. Model factories is a convenient centralized place to define how your models should be populated with fake data.


1 Answers

You can use saveMany as well. For example:

factory(User::class, 10)->create()->each(function ($user) {     $user->posts()->saveMany(factory(Posts::class, 5)->make()); }); 
like image 193
user6392101 Avatar answered Oct 05 '22 23:10

user6392101