HDTuto.com

Laravel 5 - Database seeder with insert sample user data example


This Wednesday, i will let you know how to create seeder file and why we require to create seed file in laravel. you will learn to create database seeder in your laravel application by following this article. here we will use php artisan make:seeder command for create and php artisan db:seed command for run seeder.

If you thinking why we require to create seed in laravel 5 application then i will tell you we need because if you setup your project then you will require super admin on users table. same way you have to add site settings by default like title, meta tag, logo etc. You can do it from mysql database directly but it's not way to do this. But if you create db seeder for create dummy/test users records like super admin user or settings fields etc. So you have to simple run seeder and you will get all data is ready on your database.

Here i will create very basic and simple seeder by running following command :

php artisan make:seeder DummyUsersTableSeeder

When as above command will be executed successfully then you will get "DummyUsersTableSeeder" class file in database/seeds directory, All the seeders class generated with artisan command will be place in the database/seeds folder.

Within a run method, we will write the insert query to load some user data into users table.

Ok, let's open the "DummyUsersTableSeeder.php" file and add the following line of code to insert user data.

database/seeds/DummyUsersTableSeeder.php

<?php


use Illuminate\Database\Seeder;


class DummyUsersTableSeeder extends Seeder

{

/**

* Run the database seeds.

*

* @return void

*/

public function run()

{

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

'name' => "Super Admin",

'email' => 'superadmin@gmail.com',

'password' => bcrypt('123456')

]);

}

}

There are a two way to run above created dummy seeder. So you can run by using following command for specific class.

1. Run Seeder

php artisan db:seed --class=DummyUsersTableSeeder

Other way is, you have to register your seeder on DatabaseSeeder class, here you have to define class. then you have to run whole seeder command. so first let's register seeder:

database/seeds/DatabaseSeeder.php

<?php


use Illuminate\Database\Seeder;


class DatabaseSeeder extends Seeder

{

/**

* Run the database seeds.

*

* @return void

*/

public function run()

{

$this->call(DummyUsersTableSeeder::class);

}

}

Now you can run by following way:

2. Run Seeder

php artisan db:seed

I hope you found your best solution....






January 17, 2018 | Category : PHP Laravel Laravel 5 Laravel 5.5
Related Posts