In my Controller, I need to check if a session was expired, and if so, update the value:
public function some_method(Request $request)
{
// get previous last activity
$session_last_activity = session('session_last_activity');
// update last activity to now
session(['session_last_activity'] => now());
if ($session_last_activity < now()->subMinutes(10)) {
$some_value = Str::random(30);
session(['some_value' => $some_value]);
} else {
$some_value = session('some_value');
}
// proceed to update or create some record on the DB using $some_value
}
The problem occurs when the session is expired, and there are quick multiple requests to the same page. Then, for those quick requests, each requests creates a new random string and updates the session. So the last request will have the last session value, however by that time, the database created multiple records because for each of these requests the session was expired for a moment.
For example: a user clicks example.com/page1 twice quickly while the session was expired. Now there are 2 requests that read the session as expired and set a new key and create 2 records with 2 different keys, even though there was supposed to be only one.
Can I prevent that without using Cache? This specific system does not have Cache. And also on the session side, not the DB side with locks (if possible)