Laravel 5.1 entering multiple duplicate records into a database

I wrote an application using Laravel 5.1. The application is intended for parking spaces. He "prescribes" the space by creating 3 different available slots in the database ("Morning, Day, All Day").

The problem is that with a quick page refresh, spaces are provided twice, as a result of which 6 slots are entered into the database.

However, if I refresh the page after a 5 second delay, no further entries are entered. Below is the “My” instruction, as shown below: simply not when the page / connection is quickly updated.

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()')]); } } 

Does anyone know why this could happen?

+5
source share
1 answer

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!

+1
source

Source: https://habr.com/ru/post/1235609/


All Articles