How to Use Faker in Database Seeder in Laravel

Hello Artisan,

In this quick Laravel tutorial, I will show you a quick tip that how we can use faker in our seeder file. So how to use faker in seeder Laravel tutorial, you will learn to use faker in your seeder file. So if you don't know how to use faker in database seeder in Laravel, then this example is for you.

You know that we can use faker in our factory file, but sometimes we need to use faker in our database seed file also. So I am here to show you that use of Laravel use faker outside the factory.

See the below example:

namespace Database\Seeders;

use App\Models\Category;

use Faker\Factory as Faker;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;

class CategorySeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {   
        
        DB::statement('SET FOREIGN_KEY_CHECKS=0;');
        Category::truncate();
        DB::statement('SET FOREIGN_KEY_CHECKS=1;');

        $faker = Faker::create();
        
        $a = 0;

        while ($a <= 10) {
            
            Category::create([
                'category_name' => $faker->unique()->word,
                'category_slug' => $faker->unique()->slug
            ]);

            $a++;

        }

    }
}

 

Read also: Laravel Eloquent Limit Eager Loading Data Example

 

Hope this how to use faker in seeder laravel tutorial will help you.

 

author-image
Facebook Github
A web enthusiastic, a self-motivated full-stack software engineer from Dhaka, Bangladesh with experience in developing applications using Laravel , React and Vue js