Laravel 9 Seeder and How to Seeding

  • 02-02-2023
  • 773
  • Laravel 9
  • Haresh Chauhan

In this post I will tell about laravel seeder, I will tell you how to create a seeder and its command for create seeder, then after an example of seeder how to run, call the seeder, and run the seeder using the command, call the seeder that will help us to generate dummy data or predefine data that must need to insert in the database before installing laravel application. using seeder we can insert some parts of important data that we required before running the application and fetching data from the database. for example admin login we must need to define for login, users permission that we must need to enter predefine permission before starting the laravel application.

Seeding in Laravel allows you to insert dummy data into your database for testing and development purposes. To create a seeder in Laravel 9, you can run the following command.

php artisan make:seeder UserSeeder

This will create a new seeder class in the database/seeds directory. You can define your seed data in the run method of the seeder class. For example:

database/seeds/UserSeeder.php
<?php

namespace Database\Seeders;
    
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
    
class UserSeeder extends Seeder
{
    /**
    * Run the database seeders.
    *
    * @return void
    */
    public function run()
    {
        DB::table('users')->insert([
            'name' => Str::random(10),
            'email' => Str::random(10).'@gmail.com',
            'password' => Hash::make('password'),
        ]);
    }
}

To execute, the seeder code hit the below command in your laravel application terminal. This command will run the seeder that provided the name.

php artisan db:seed --class=UserSeeder

You can also run all of your seeders at once using the db:seed command without any arguments, but for that you first need to define seeder class name in the DatabaseSeeder.php

DatabaseSeeder.php
<?php

use Illuminate\Database\Seeder;

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

After defining all seeder in DatabaseSeeder.php class, run below command.

php artisan db:seed

We always thanks to you for reading our blogs.


dharmesh-image

Dharmesh Chauhan

(Swapinfoway Founder)

Hello Sir, We are brothers origin from Gujarat India, Fullstack developers working together since 2016. We have lots of skills in web development in different technologies here I mention PHP, Laravel, Javascript, Vuejs, Ajax, API, Payment Gateway Integration, Database, HTML5, CSS3, and Server Administration. So you need our service Please Contact Us

haresh-image

Haresh Chauhan

(Co-Founder)


We Are Also Recommending You :