How to create table seeder in Laravel 4.2 - BOOKC -->

How to create table seeder in Laravel 4.2

Saturday, March 25, 2017


Seeding is the technique of filling our database with sample data so we can test and create our applications. It really does make building applications much easier.

In laravel 4.2 there is no artisan command to generate the seeder file, so we have to do it manually, we can put anything as the name for our seeder, but it always a good practice to follow the rule of class name, after all seeder is a class.

Let' say i want to create a seeder for filling table users in my application, so the name should be UserTableSeeder.php or TableUserSeeder.php, something like that. Make sure you put it under app/database/seeds/ folder.

Here's an example of seeder for single record
<?php
/**
* Seeder for table `user`
*
*/
class UserTableSeeder extends Seeder
{
public function run()
{
$this->command->info('Seeding user table...');
// seeding for user john wick
$userExist = User::where('name', '=', 'john wick')
->where('email', '=', 'john.wick@gmail.com')
->first();

if (! $userExist) {
$this->command->info(sprintf(' Creating record for user %s.', 'john wick'));
$newUser = new User();
$newUser->name = 'john wick';
$newUser->email = 'john.wick@gmail.com';
$newUser->password = Hash::make('123');
$newUser->save();
} else {
$this->command->info(sprintf(' User %s already exist', 'john wick'));
}
}
}

Here's an example of seeder for multiple record
<?php
/**
* Seeder for table `user`
*
*/
class UserTableSeeder extends Seeder
{
public function run()
{

$data = array(
1 => array('name' => 'john wick',
'email' => 'john.wick@gmail.com',
'password' => Hash::make('123')),
2 => array('name' => 'jenny lee',
'email' => 'jenny@gmail.com',
'password' => Hash::make('123')),
3 => array('name' => 'emma watson',
'email' => 'emma@yahoo.com',
'password' => Hash::make('123'))
);

$this->command->info('Seeding user table...');

foreach( $data as $key => $value) {

$name = $data[$key]['name'];
$email = $data[$key]['email'];
$password = $data[$key]['password'];

$userExist = User::where('name', '=', $name)
->where('email', '=', $email)
->first();

if (! $userExist) {
$this->command->info(sprintf(' Creating record for user %s.', $name));
$newUser = new User();
$newUser->name = $data[$key]['name'];
$newUser->email = $data[$key]['email'];
$newUser->password = $data[$key]['password'];
$newUser->save();
} else {
$this->command->info(sprintf(' User %s already exist', $name));
}
}

}
}

How to run the database seeder?
We are finish creating the seeder class but we haven't run it yet, so currently we won't be able to see the result on the table users yet. We need to run artisan command that will execute the seeder.

running the seeder:
php artisan db:seed --class=[name-of-the-seeder-class]

Example:
php artisan db:seed --class=UserTableSeeder
php artisan db:seed --class=TableUserSeeder