Generating Fake Data in Laravel Using Seeders

tahsin000

Tahsin Abrar

Posted on April 25, 2024

Generating Fake Data in Laravel Using Seeders

Step 1: Create Seeders

Run the following Artisan command to create seeders for your courses and services:

php artisan make:seeder CoursesSeeder
php artisan make:seeder ServicesSeeder
Enter fullscreen mode Exit fullscreen mode

Step 2: Define Seeders

Open the generated seeder files (database/seeders/CoursesSeeder.php and database/seeders/ServicesSeeder.php) and define the logic to insert fake data into the respective database tables. You can use the Faker library to generate fake data.

Here's an example of how you can define the run() method in your CoursesSeeder seeder:

use Illuminate\Database\Seeder;
use App\Models\Course;
use Faker\Factory as Faker;

class CoursesSeeder extends Seeder
{
    public function run()
    {
        $faker = Faker::create();

        foreach (range(1, 10) as $index) {
            Course::create([
                'course_name' => $faker->name,
                'course_description' => $faker->sentence,
                'course_fee' => $faker->randomNumber(4),
                'course_total_enroll' => $faker->randomNumber(3),
                'course_total_class' => $faker->randomNumber(2),
                'course_link' => $faker->url,
                'course_image' => $faker->imageUrl(),
            ]);
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 3: Call Seeders

Open the DatabaseSeeder.php file located in database/seeders directory and call your seeder classes:

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run(): void
    {
        $this->call([
            CoursesSeeder::class,
            ServicesSeeder::class
        ]);
    }
}
Enter fullscreen mode Exit fullscreen mode

Step 4: Run Seeders

Execute the following Artisan command to run the seeders and populate your database with fake data:

php artisan db:seed
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
tahsin000
Tahsin Abrar

Posted on April 25, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related