I have been writing a lot about Laravel lately and recently I was asked about database table seeding. Chances are you already use the awesome migrations feature, but probably don’t use database seeding. I have seen people using migrations to seed a table, but it’s messy and not exactly ideal. Using the seeding functionality in Laravel, you’ll discover how easy it actually is.
When should I use seeding?
I personally use seeding in Laravel quite extensively during the development phase of a web application. Being able to add in mock user accounts, pages and other data for testing purposes is a lot easier than manually doing it every time.
Another use that I find myself using is seeding roles and permissions. In my web applications, I will generally have a basic set of permissions that every Laravel site will get (admin, guest and basic user roles) as well as some basic permissions.
A precursor
Where to put your seed files?
All custom seeding classes go into app/database/seeds
a new installation of Laravel 4 will have a file called DatabaseSeeder
which is where we will call our custom created seed class(es) to fill our database with content.
What do I name them?
The name of your custom seeding class does not matter. However, it is advisable to name your seeding classes in camelCase. If you are wanting to seed a roles table in your application, you would call it something like RolesTableSeeder
or SeedRolesTable
In action
Now we’ve explained the basics, when to use seeding and how it can help us, lets get to the meat of the post.
Rather than explain step-by-step, I’ll show an example of using seeding instead.
The custom role seeding file app/database/seeds/RoleTableSeeder.php
Calling our newly created seeding file
In the file app/database/seeds/DatabaseSeeder.php
you will notice a run function. Within this function beneath the Eloquent::unguard function call, we will call our seeding file.