How to seed a database in Laravel 5 (without the “[ReflectionException] Class ____ does not exist” error)

Posted on February 24, 2015 in Web Dev

Database seeding in Laravel is pretty awesome. It had me pondering recently what the best practice is for seeding a database with an admin user (or users). During my development I run into a slight issue. I felt like the Laravel docs didn’t fully explain the process, so I’m going to show you my solution below.

Originally I was adding my seed class to the DatabaseSeeder.php file simply as an extra class. However, this is wrong. New seed classes need to go into their own file. I repeat; your own new seed classes need to go into their own file.

Let’s say I’m using the amazing Entrust package and want to seed my database with one admin user. First you need to create a new seed class file in the same directory as DatabaseSeeder.php. For example:


/App

/Database

/Database/Seeds

/Database/Seeds/DatabaseSeeder.php

/Database/Seeds/AdminUserSeeder.php

Then you need to call this class from within DatabaseSeeder.php:


class DatabaseSeeder extends Seeder {

public function run()
{
Model::unguard();

$this->call('AdminUserSeeder');
}

}

And here’s what my AdminUserSeeder.php class looks like:


<?php

use Illuminate\Database\Seeder;
use Illuminate\Database\Eloquent\Model;

use Zizaco\Entrust\EntrustRole;
use Zizaco\Entrust\EntrustPermission;
use Zizaco\Entrust\HasRole;
use App\Models\User;

class AdminUserSeeder extends Seeder {
public function run()
{
Role::firstOrCreate([
'name' => 'admin_role_name',
'display_name' => 'Super Admin',
'description' => 'The highest level of admin-ness',
]);

$superadmin = Role::where('name','=','admin_role_name')->first();
$shrek = User::where('username','=','shrek77')->first();

if (!$shrek->hasRole('admin_role_name')) {
$joe->attachRole( $superadmin->id );
}

$this->command->info('Admin user seeded :-)');
}
}

Dont’ forget that in Laravel 5 you’ll need to add all the ‘use’ statement at the start of the file to prevent the “Class not found” errors.

As an added bonus, make sure you make full use of “Command->info” to echo into the terminal some info about the success of the seed.

Now, when I run:

php artisan db:seed --class=AdminUserSeeder

My database gets seeded, and I get a nice little message back telling me what’s happened. I also start searching more details about different databases including NoSQL database.

Leave a comment

Was this helpful? Did I miss something? Do you have a question? Get in touch, or tell me below.