DEV Community

Peter Fox
Peter Fox

Posted on • Originally published at Medium on

Laravel Console: Options for your Seeders


Photo by Nikola Jovanovic on Unsplash

Seeding the Laravel database can often be a bit of a chore. It’s fine for small projects but it becomes a pain when you want some flexibility or more complex examples. For instance maybe you want a command option to set an initial size for how many users should be added when running a seeder.

For example maybe we want this code to work:

But then when we run it we get the following error:

Well it’s actually surprisingly simple to fix this and make it work and only requires an extra bit of code to our app/Providers/AppServiceProvider.php.

Let’s do the following to our AppServiceProvider.

As you can see we’ve played with the command as accessed via the service container so when the seeding command is created we add the additional options that will then be equally available to our seeders.

From now on our seeding code behaves as expected.

There is sadly, one draw back, currently adding such changes to migration commands would work the same way but would equally require you to then extend the command completely to provide the code to pass these new options into the seeding command at the time of running, which is not overly hard but I won’t be covering it here.

Conclusion

This trick can be quite useful at times as it adds an extra layer of flexibility to your Laravel app. Seeding is quite a complex process at times and different apps require different things so it’s good to make use of this to customise as your needs change.

I’m Peter Fox, a software developer in the UK who works with Laravel among other things. Thank you for reading my article, I’ve got several more on both medium and dev.to. If you want to know more about me, head over to https://www.peterfox.me. I’m also now also Sponsorable on GitHub. If you’d like to encourage me to write more articles like this please do consider dropping a small one off donation.

Top comments (0)