Skip to content

Commit cfd08c8

Browse files
committed
feat: Implement cached product listing using cursor pagination and invalidate cache upon product model saves.
1 parent 7dd48e4 commit cfd08c8

2 files changed

Lines changed: 18 additions & 1 deletion

File tree

app/Http/Controllers/Product/ProductListController.php

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
use App\Models\Product;
88
use Illuminate\Http\Request;
99
use Illuminate\Database\Eloquent\Builder;
10+
use Illuminate\Support\Facades\Cache;
1011
use Illuminate\Support\Facades\Log;
1112

1213
class ProductListController extends Controller
@@ -148,7 +149,14 @@ public function allProducts(Request $request)
148149
}
149150
}
150151

151-
$products = $query->paginate(6);
152+
$cursor = $request->query('cursor', 'default');
153+
154+
$cacheKey = "products_list_v1_" . $cursor;
155+
156+
$products = Cache::remember($cacheKey, now()->addMinutes(10), function () use ($query) {
157+
return $query->cursorPaginate(20);
158+
});
159+
152160

153161
return ProductResource::collection($products);
154162
}

app/Models/Product.php

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
use Illuminate\Database\Eloquent\Relations\BelongsTo;
2020
use Illuminate\Database\Eloquent\Factories\HasFactory;
2121
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
22+
use Illuminate\Support\Facades\Cache;
2223

2324
class Product extends Model
2425
{
@@ -142,6 +143,14 @@ public function getVariations()
142143
});
143144
}
144145

146+
protected static function booted()
147+
{
148+
static::saved(function ($product) {
149+
150+
Cache::flush();
151+
});
152+
}
153+
145154
public function wholesalePrices()
146155
{
147156
return $this->morphMany(WholeSalePrice::class, 'priceable');

0 commit comments

Comments
 (0)