Marco Aurélio Deleu Marco Aurélio Deleu - 1 month ago 9
PHP Question

DB::table Vs Eloquent Model - Laravel Database Seed

When researching for Database Seeder, it's common to see people using

DB::table('my_table')->insert(['column' => 'value'])
in the Seeder classes. I'd like to know the reasoning behind this apparent convention as to why I should use
DB::*
instead of
MyModel::*
to perform such tasks.

Answer

Most importantly, because with DB inserts, you can do multiple inserts at once. Especially when seeding many large tables, that's much, much faster than doing one query per insert.

http://laravel.com/docs/master/queries#inserts

DB::table('users')->insert([
    ['email' => 'taylor@example.com', 'votes' => 0],
    ['email' => 'dayle@example.com', 'votes' => 0]
]);

You also don't need to load the Eloquent class or any of the bulk that comes with it. Again, seeding thousands of rows, creating thousands of Eloquent objects... that can take up a lot of memory.

And finally, if there do happen to be bugs or issues with the Eloquent models, your seeds will still work.


There are some downsides. For example if one of your Eloquent models overrides a setter to manipulate and format data before being saved, then you lose that convenience.

And actually, that applies to any model with $timestamps; with DB inserts you'll have to set the created_at and updated_at timestamps manually. But with a seeder, you might want to simulate that items were created days or months or years ago, in which case you wouldn't want those timestamps to be set automatically.


But actually, a lot of people do use model factories. If you do want to use your setters, or automatically assign relationships, and basically take advantage of everything Eloquent offers, then they're great to use for seeding. With the efficiency tradeoffs I mentioned, but sometimes that's worth it.