Laravel 5 - Example of Database Seeder with insert sample data

By Hardik Savani | February 23, 2017 | | 79704 Viewer | Category : Laravel


We should know what is database seeder in laravel and why we should use before start example of database seeding. Laravel provides a tool to add sample or dummy data to our databases automatically. that is call it database seeding.

Laravel database seeder through we can add simply testing data on our database table. Database seed is extremely useful because testing with various data allows you to likely detect bugs you otherwise would have overlooked. We have to simple make one time seeder with some dummy data, that way we can simply reuse when you deploy project first time. We can make seeder after migration of table.

So today in this example we will add some sample data of users table from scratch. So laravel provide us command for creating seed and run that. so first run bellow command for create "UsersTableDataSeeder" seeder.

Make Seeder

php artisan make:seeder UsersTableDataSeeder

After run above command successfully, you will be found new created file "database/seeds/UsersTableDataSeeder.php". In this file i make three sample user for users table using insert query. So open UsersTableDataSeeder.php file and some sample data like as bellow:

database/seeds/UsersTableDataSeeder.php

<?php


use Illuminate\Database\Seeder;


class UsersTableDataSeeder extends Seeder

{

/**

* Run the database seeds.

*

* @return void

*/

public function run()

{

for ($i=0; $i < 3; $i++) {

DB::table('users')->insert([

'name' => str_random(8),

'email' => str_random(12).'@mail.com',

'password' => bcrypt('123456')

]);

}

}

}

Now we are ready to run above seeder using bellow command:

Run Seeder:

php artisan db:seed --class=UsersTableDataSeeder

I hope it can help you...



Hardik Savani
My name is Hardik Savani. I'm a full-stack developer, entrepreneur and owner of Aatman Infotech. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.
Follow Me: Github Twitter
***Do you want me hire for your Project Work? Then Contact US.


We are Recommending you: