4

In Laravel we have the concept of seeding data that is used in conjunction with model factories in order to populate data for testing environment.

How should we proceed (where to put the code) when we need to populate data for production? For example I might have a permission table, and I need to add some default permissions along with the schema creation. After a while I might need to add to my app a new permission. Should these data insertion stay together with the migrations?

What mechanism should we use for inserting data? Models or data array? My problem with data array is that no business from models, will be helpful: like: casts or relationships.

I know, that there two discussions about this subject, but for me the solutions do no cover all the problems:

Community
  • 1
  • 1
user237329
  • 809
  • 1
  • 10
  • 27

1 Answers1

3

How should we proceed (where to put the code) when we need to populate data for production?

Our team makes a brand new migration for inserting production seeds (separate from the migration that creates the table). That way, if you need to add more seeds to your production data in the future, you can simply make a new standalone migration.

For example, your first migration could be 2016_03_05_213904_create_permissions_table.php, followed by your production seeds: 2016_03_05_214014_seed_permissions_table.php.

You could put this data in the same migration as your table creation, but in my opinion, the migration becomes less readable and arguably violates SRP. If you needed to add more seeds in the future, you would have two different "standards" (one group of seeds in your original migration, and another in a separate migration).

To answer your second question:

What mechanism should we use for inserting data?

I would always use your model's create() method for inserting production seeds. This ensures that any event listeners that are listening for your model's creation event properly fire. As you said, there could be extra code that needs to fire when your model is created.


ssfinney
  • 305
  • 3
  • 7