Generating Fake Data in Laravel Using Seeders

RMAG news

Step 1: Create a Seeder

Run the following Artisan command to create a seeder:

php artisan make:seeder CourseSeeder

Step 2: Define the Seeder

Open the generated seeder file (database/seeders/CourseSeeder.php), and define the logic to insert fake data into the database table. You can use the Faker library to generate fake data. Here’s an example of how you can define the run() method in your seeder:

use IlluminateDatabaseSeeder;
use AppModelsCourse;
use FakerFactory as Faker;

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

foreach (range(1, 10) as $index) {
Course::create([
‘course_name’ => $faker->name,
‘course_des’ => $faker->sentence,
‘course_fee’ => $faker->randomNumber(4),
‘course_totalenroll’ => $faker->randomNumber(3),
‘course_totalclass’ => $faker->randomNumber(2),
‘course_link’ => $faker->url,
‘course_img’ => $faker->imageUrl(),
]);
}
}
}

Step 3: Call the Seeder

You can call your seeder class from the DatabaseSeeder class (database/seeders/DatabaseSeeder.php) or directly from the command line.

If you want to call it from DatabaseSeeder:

Open the DatabaseSeeder.php file.
Uncomment the $this->call([CourseSeeder::class]); line within the run() method.

If you want to call it directly from the command line:

php artisan db:seed –class=CourseSeeder

Step 4: Run the Seeder

Execute the following Artisan command to execute the seeder:

php artisan db:seed

#Laravel #Seeders #FakeData #Database #Development #Testing #Faker

Leave a Reply

Your email address will not be published. Required fields are marked *