The code should do the following:
- If the cache is empty, get from database
- Create order
- Push order to cache and save it in database
- Redirect user
How can I keep the cache sync with database to avoid errors?
code
$maxLock = 60;
$lock = Cache::lock("cacheLock", $maxLock);
$lock->block($maxLock);
$cachedIds = Cache::get("cachedIds");
if (empty($cachedIds)) {
$cachedIds = $product
->orders()
->whereNot('status', 'expired')
->implode('id', ',');
$cachedIds = empty($cachedIds)
? []
: explode(',', $cachedIds);
}
$order = new ProductOrder();
$order->fill($request->all());
$order->save();
Cache::put("cachedIds", array_merge($cachedIds, [$order->id]), 60 * 60);
return to_route('checkout', $product->url);
The fact you do
$product->orders()implies you're keeping one cached entry per product. Is that right? In any case, you can useCache::remember(key, ttl, callback)to achieve what you want.Let's say for this example
$product's id is 1And then every time you do something that would alter this value, simply use
Cache::forget().