March 30, 2020

Easy Seeding with var_export()

Create seeders for your existing data in literal seconds.

Everyone who's spent more than a minute trying to debug a PHP script has probably used var_dump() at some point. Especially if you've yet to figure out more advanced tools like xdebug - but did you know about var_export()?

I'd never really paid it much attention until just a few days ago, when it was brought up in this RFC: Change var_export() array syntax to use shorthand arrays when I realized it could serve a common use in modern PHP frameworks like Laravel - generating seeders.

Imagine you're creating a CMS for a client. You're several sprints down, they're interacting with your beta code in a staging environment and creating a simulacrum of their live data to test with. You're going to be breaking and re-creating this environment a lot and keeping a persistent DB leads to functional errors caused by bad data from old builds, but you don't want to frustrate your client by making them re-enter the same data - so you create some seeders.

Now, you could export their data as a csv, run it through a conversion using a text editor, or save the csv and even parse it in your seeder files... or you could write two lines of code and copy & paste the output:

Again, everything that comes from var_export is perfectly valid, executable PHP code. In fact if you're using Laravel, you can grab the array representation of a collection like this screenshot and paste it directly into DB::table()->insert() for your seeder (assuming your timestamps are in a format your database engine parses):

Couldn't be easier.