Laravel: Get a better Seeder for free
The default seeder is too barebones for any developer
Dealing with seeders at the first steps of your application development can be a pain when your models are not that simple. More often than not you will find yourself trying to seed Models only to receive exceptions left and right. You will feel like Neo when he didn’t make the jump his first time.
Indeed, if your seeders throw an Exception, Laravel’s Seeder will become a pain to work with:
- You can’t continue a previously failed seeding.
- You have to wrap all your seeding operations in a transaction.
- You only have one entry point for seeding.
Seeding in Laravel feels barebones at times, but luckily I made for you, totally free of charge, a great Seeder that overrides the default with a few creative ways to tackle these problematics. It’s the same that Larawiz uses for all apps that creates.
It’s makes your seeders much simpler to understand too:
<?php
namespace Database\Seeders;
use App\Models\User;
use Database\Factories\UserFactory;
class UserSeeder extends Seeder
{
protected string $model = User::class;
public function before()
{
$this->skipWhen(User::query()->exists());
}
public function seed(UserFactory $factory)
{
$factory->count($this->pages(2.5))->create();
}
public function seedTrashed(UserFactory $factory)
{
$factory->count(5)->trashed()->create();
}
}
This seeder solves the three key problems of Laravel’s vanilla Seeder with new features:
- It runs all methods that start with
seed
, likeseed()
andseedTrashed()
. - All the methods run inside a DB Transaction by default.
- You can skip a seeding method or the whole seeder.
- You can make checks before and after the seeder runs.
The documentation is on Larawiz, but if you already are working on an application, you may just copy-paste the gist in your database\Seeders
directory and let your seeders to extend it: