Laravel Database Seeding

Posted in Web Development

In this article,I’ll explain laravel feature called database seeding.This feature helps us to insert multiple test data in tables without need to do it manually row by row in database.

So let’s start laughing

open your terminal and run this command to create a new laravel project

composer create-project --prefer-dist laravel/laravel laravel-db-seeds

 

Make sure you installed all laravel dependiencies before running this command https://laravel.com/docs/5.6/installation

cd laravel-db-seeds folder in terminal and run this command to run application in your browser

php artisan serve

 

The application will run in browser url http://127.0.0.1:8000/

 

To run database migration,create new database "dbseeds" in mysql then edit .env file with

DB_CONNECTION=mysql

DB_HOST=127.0.0.1

DB_PORT=3306

DB_DATABASE=dbseeds

DB_USERNAME=root

DB_PASSWORD=

 

 

Then run this command in terminal

php artisan migrate

 

 

Open "dbseeds" database you’ll notice new users table created cause laravel by default has users table migration file.

Make controller that retrieve all users data, create new file in this path /app/Http/Controllers/UserController and write this code in it

<?php

namespace App\Http\Controllers;

use App\User;

class UserController extends Controller

{

public function index(){

$users= User::all();

return view('users',compact('users'));

}

}

 

 

Let’s add our route in web.php file inside routes folder that return users data

Route::get('/users', 'UserController@index');

 

To return all data in list view,create new file inside resources/views/users.blade.php and paste this code

<!doctype html>

<html lang="{{ app()->getLocale() }}">

<head>

<meta charset="utf-8">

<meta http-equiv="X-UA-Compatible" content="IE=edge">

<meta name="viewport" content="width=device-width, initial-scale=1">

<title>Database Seeding</title>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

</head>

<body class=" container mt-5">

<h1 class="text-center text-info ">

Users

</h1>

<ul class="list-group">

@foreach($users as $user)

<li class="list-group-item list-group-item-info">

<div class="d-flex w-100 justify-content-between">

<h5 class="mb-1">{{$user->name}}</h5>

<p class="mb-1">{{$user->email}}</p>

<small> {{$user->created_at->diffForHumans()}}</small>

</div>

</li>

@endforeach

</ul>

</body>

</html>

 

if you navigate to your browser url http://127.0.0.1:8000/users

You’ll see list is empty cause no data in users table to be retrieved.Now it’s time to fill our database using UserTableSeeder class run this command in terminal to create seeder.

php artisan make:seeder UsersTableSeeder

 

You’ll find new file created "UserTableSeeder.php" placed in the database/seeds/ directory.A seeder class only contains one method by default "run".This method is called when run php artisan db:seed.Inside the run method, you may insert data into your database however you wish using two ways.

Way 1: Query Builder

Using this method you manually insert data by specifying the attributes for each model.

Edit UsersTableSeeder by adding a database insert statement to run method like that.

public function run(){

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

'name'=> str_random(10),

'email'=> str_random(10).'@gmail.com',

'password'=> bcrypt('secret'),

'created_at'=> Carbon\Carbon::now()

]);

}

 

Then go to the main DatabaseSeeder file that call all seeders and uncomment this line in run method $this→call(UsersTableSeeder::class);

To implement this seed,run this command in terminal

php artisan db:seed

 

Refresh the browser you’ll see one user has been inserted to db.

Way2: Eloquent Model Factories

Instead of manually specifying the value of each column when you create this test data, Laravel allows you to define a default set of attributes for each of your Eloquent models using model factories. To get started, take a look at the database/factories/UserFactory.php file in your application. Out of the box, this file contains one factory definition:

use Faker\Generator as Faker;

$factory->define(App\User::class, function (Faker $faker) {

return [

'name' => $faker->name,

'email' => $faker->unique()->safeEmail,

'password' => '$2y$10$TKh8H1.PfQx37YgCzwiKb.KjNyWgaHb9cbcoQgdIVFlYg7B77UdFm', // secret

'remember_token' => str_random(10), ]; });

 

Faker PHP library, which allows you to generate various kinds of random data for testing.All of the files within the factories directory will automatically be loaded by Laravel.

Just add line after password to insert created_at column like that

$factory->define(App\User::class,

function (Faker $faker) {

return

[

'name'=> $faker->name,

'email'=> $faker->unique()->safeEmail,

'password'=> '$2y$10$TKh8H1.PfQx37YgCzwiKb.KjNyWgaHb9cbcoQgdIVFlYg7B77UdFm',

'created_at'=>Carbon\Carbon::now(),

'remember_token'=> str_random(10),

];

});

 

To create fake 30 users test data,edit run method in UsersTableSeeder file

public function run()

{

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

// 'name' => str_random(10),

// 'email' => str_random(10).'@gmail.com',

// 'password' => bcrypt('secret'),

// 'created_at' => Carbon\Carbon::now()

// ]);

factory(App\User::class, 30)->create();

}

 

 

Now you may use the db:seed Artisan command to seed your database. By default, the db:seed command runs the DatabaseSeeder class, which may be used to call other seed classes. However, you may use the --class option to specify a specific seeder class to run individually.

php artisan db:seed

php artisan db:seed --class=UsersTableSeeder

 

Sometimes db:seed may not work due to class file not being affected so to overcome that issue we have to execute composer dump-autoload command.

Refresh the browser to see the 30 users test data results in just seconds cool

Conclusion

Hope this article help you to understand about database seeding feature in Laravel and you can read more about database seeding from this reference  https://laravel.com/docs/5.6/seeding.Also you can access this project files from https://gitlab.com/ayamostafa/laravel-db-seeds If you clone this project, don’t forget to run "composer install" first before running it in the browser.

good byesmile

Comments


No Comments

- Please, Login to fully participate in discussion .

LEAVE A COMMENT

Cancel