When you deal with such a problem, database transactions are often part of the solution. The code will look something like this:
DB::transaction(function () use ($bays, $date){ foreach($bays as $bay) { if(!BookingDates::where('date', $date)->where('parking_bay', $bay->number)->count()) { BookingDates::insert(['parking_bay' => $bay->number, 'date' => $date, 'slot' => 'Morning', 'time' => '7am - 1pm', 'status' => 'Available', 'created_at' => DB::raw('now()')]); BookingDates::insert(['parking_bay' => $bay->number, 'date' => $date, 'slot' => 'Afternoon', 'time' => '1pm - 7pm', 'status' => 'Available', 'created_at' => DB::raw('now()')]); BookingDates::insert(['parking_bay' => $bay->number, 'date' => $date, 'slot' => 'All Day', 'time' => null, 'status' => 'Available', 'created_at' => DB::raw('now()')]); } } });
To ensure data integrity, you will also want to define a unique index in the parking_bay, date, and slot columns. You may need to go beyond the migration API and simply execute the SQL statement in your migration, which will depend on whether you use MySQL, MSSQL, Postgres, etc.
Between transactions and a unique index, the database refuses to insert duplicate rows and rolls back the bad insert, so you won’t get hung up on something like one person having a morning slot and the other all day.
Let me know if you need more help!
source share