gpt-3.5-turbo-0301· OpenAI
WildChat-4.8M (AI2)
Laravel how can I make controller execute one at a time? So if user1 execute controller…
- User
Laravel how can I make controller execute one at a time? So if user1 execute controller action, second user should wait
- Assistant
To make a controller action execute one at a time, you can implement a locking mechanism using Laravel's built-in
Cachesystem.Here's an example of how you can do this:
- In your controller action, start by defining a unique cache key that identifies the resource or process that you want to lock:
$cacheKey = 'resource_lock_' . $id;- Check if the cache key already exists. If it does, it means another user is already executing the same controller action. In this case, you can either return an error message or wait for the lock to be released.
if (Cache::has($cacheKey)) { return response()->json(['message' => 'Resource is currently locked. Please try again later.'], 403); }