Laravel 4 database seeding example

Database seeding is a convenient way to fill Laravel 4 application with test data, this can be useful while application developing, or testing. In provided example ‘users’ table will be seeded with test user data. Example table was previously created with Laravel Migrations which is described in this post.

First create seeding class for the table under app/database/seeds directory, in this case UserTableSeeder.php

class UserTableSeeder extends Seeder {

	public function run() {
		// delete existing db rows
		DB::table('users')->delete();
		// create new user
		User::create(array(
			'name' => 'test user 1',
			'email' => 'foo@bar.com',
			'password' => Hash::make('password')
		));
	}

}

Method run() deletes all existing users, then creates new user row with provided name, email and password (hashed with Hash::make() function). Please note that ‘User::create’ requires User model to be set up. By default User model is created in app/models, so there is no need of doing that in this particular case.

Next we need to add new seeder class to app/database/seeds/DatabaseSeeder.php

class DatabaseSeeder extends Seeder {

	/**
	 * Run the database seeds.
	 * @return void
	 */
	public function run() {
		Eloquent::unguard();
		$this->call('UserTableSeeder');
	}

}

And this is it, now simply call the following artisan command

$ php artisan db:seed

And check if users table contains test data

mysql> select * from users;
+----+-------------+-------------+--------------------------------------------------------------+----------------+---------------------+---------------------+
| id | name        | email       | password                                                     | remember_token | created_at          | updated_at          |
+----+-------------+-------------+--------------------------------------------------------------+----------------+---------------------+---------------------+
|  1 | test user 1 | foo@bar.com | $2y$10$e2hVN4Yf7.aEOHiVRmN5XORQcuIaHUDege5V9i9792Wfx8DFe03W2 | NULL           | 2014-08-10 14:11:02 | 2014-08-10 14:11:02 |
+----+-------------+-------------+--------------------------------------------------------------+----------------+---------------------+---------------------+

Leave a Reply

Your email address will not be published. Required fields are marked *