Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

fahaddsheikh's avatar

Eloquent query for 2 tables in database seeding

I have courses and events. Both courses and events will have batches. For database seeding I need to generate a random id for existing courses or events in the batches table. So each batch could randomly be assigned to either a course or an event. I am able to randomly pull an event or a course but I unable to pull a random from both. Please Help.

I am using the following code

$factory->define(App\Batch::class, function ($faker) {

    // Random datetime for starting date within a week
    $startingDate = $faker->dateTimeBetween('this week', '+6 days');
    // Random datetime for ending date of the current week *after* `$startingDate`
    $endingDate   = $faker->dateTimeBetween($startingDate, '+3 months');

    // Random datetime for starting time
    $startingTime = $faker->dateTimeBetween('this week', '+1 hours');
    // Random datetime of ending time from the starting
    $endingTime   = $faker->dateTimeBetween($startingTime, '+3 hours');

    return [
        'user_id'       => App\User::all()->random()->id,
        'parent_id'     => App\Course::all()->random()->id,
        'start_date'    => $startingDate,
        'end_date'      => $endingDate,
        'start_time'    => $startingTime,
        'end_time'      => $endingTime,
        'start_day'     => $faker->dayOfWeek,
        'end_day'       => $faker->dayOfWeek,
        'price'         => $faker->numberBetween($min = 1, $max = 10) * 100 
    ];
});
0 likes
0 replies

Please or to participate in this conversation.