Laravel 8 Database Seeder Example

In this tutorial, we will see the laravel 8 database seeder example, as we all know laravel framework provides many functionalities to the user to reduce the developer's time for developing the website. So, here we will see how to create a database seeder in Laravel 8.

Many times you have a requirement to add some default records or entries to login or add form details etc. there is no problem adding manual data in the database one or two times but it is a very challenging task to add data manually each and every time.

Laravel includes the ability to seed your database with data using seed classes. All seed classes are stored in the database/seeders directory. By default, a DatabaseSeeder class is defined for you. So, if you want to avoid this boring task you need to create database seeders in laravel, laravel provides an inbuilt command to create database seeders in laravel 8.

Let's see how to create a database seeder in laravel 8.

Run the following command in your terminal to create a seeder in laravel application.

php artisan make:seeder UserSeeder

 

 

It will create one file UserSeeder.php on the seeds folder. All seed classes are stored in the database/seeds directory. 

Add your data as per your requirement like below in this path database/seeds/UserSeeder.php

<?php
  
use Illuminate\Database\Seeder;
use App\Models\User;
   
class UserSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        User::create([
            'name' => 'test',
            'email' => 'test@gmail.com',
            'password' => bcrypt('123456'),
        ]);
    }
}

Now run the below command in your terminal

php artisan db:seed --class=UserSeeder

Or you can declare your seeder in the DatabaseSeeder class file. then you have to run a single command to run all listed seeder classes.

<?php
  
use Illuminate\Database\Seeder;
   
class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
        $this->call(UserSeeder::class);
    }
}

 

 

and run the below command in your terminal. 

php artisan db:seed

 


You might also Like :

techsolutionstuff

Techsolutionstuff | The Complete Guide

I'm a software engineer and the founder of techsolutionstuff.com. Hailing from India, I craft articles, tutorials, tricks, and tips to aid developers. Explore Laravel, PHP, MySQL, jQuery, Bootstrap, Node.js, Vue.js, and AngularJS in our tech stack.

RECOMMENDED POSTS

FEATURE POSTS