🧠 1. Cache কী এবং কেন ব্যবহার করবো?
Cache হলো এমন একটা system যেখানে database থেকে বারবার data না এনে memory থেকে দ্রুত data আনা হয়।
👉 এতে performance অনেক বেড়ে যায়
⚡ 2. Cache::rememberForever (Basic Usage)
use Illuminate\Support\Facades\Cache;
use App\Models\Product;
$products = Cache::rememberForever('active_products', function () {
return Product::with('category')->where('active', 1)->get();
});
🧠 এটা কী করে?
- প্রথমবার DB থেকে data নেয়
- পরে cache থেকে data দেয়
- manual clear না করলে forever থাকে
⚠️ Problem
Product update হলে cache update হয় না ❌
🚀 3. Trait তৈরি করা (Reusable Cache Clear)
📍 app/Traits/ClearsCache.php
namespace App\Traits;
use Illuminate\Support\Facades\Cache;
trait ClearsCache
{
protected function clearCache(string $key): void
{
Cache::forget($key);
}
}
🧩 4. Observer (Automatic Cache Clear)
📍 Create observer:
php artisan make:observer ProductObserver --model=Product
✍️ Observer code:
namespace App\Observers;
use App\Models\Product;
use App\Traits\ClearsCache;
use App\Events\ProductUpdated;
class ProductObserver
{
use ClearsCache;
protected function clearAll(): void
{
$this->clearCache('active_products');
}
public function created(Product $product)
{
$this->clearAll();
event(new ProductUpdated());
}
public function updated(Product $product)
{
$this->clearAll();
event(new ProductUpdated());
}
public function deleted(Product $product)
{
$this->clearAll();
event(new ProductUpdated());
}
}
🔗 Register Observer
📍 AppServiceProvider.php
use App\Models\Product;
use App\Observers\ProductObserver;
public function boot(): void
{
Product::observe(ProductObserver::class);
}
🚀 5. Filament Cache Usage
use Illuminate\Support\Facades\Cache;
use App\Models\Product;
public static function getEloquentQuery()
{
return Cache::rememberForever('active_products', function () {
return Product::with('category')->where('active', 1);
});
}
⚡ 6. Livewire Event Listener (UI Auto Refresh)
📍 ListProducts.php
protected $listeners = ['productUpdated' => '$refresh'];
🧩 Bridge Event
use Illuminate\Support\Facades\Event;
use App\Events\ProductUpdated;
public function mount(): void
{
parent::mount();
Event::listen(ProductUpdated::class, function () {
$this->dispatch('productUpdated');
});
}
🔄 FINAL FLOW
Admin updates product
↓
Observer runs
↓
Cache cleared
↓
Event fired
↓
Livewire catches event
↓
UI refresh ($refresh)
↓
User sees updated data
🎯 Best Practices
✅ Cache naming
Good:
- active_products
- active_products_with_category
Bad:
- data1
- temp
✅ Always clear cache on mutation
- create
- update
- delete
✅ Use Observer (not controller)
✔ clean
✔ scalable
🏁 Final Summary
Cache = speed ⚡
Observer = freshness 🔄
Trait = reuse ♻️
Event = communication 📡
Livewire = UI update 🎯
"Cache speeds up reading, Observer keeps it fresh, Livewire updates UI"