When data changes, you must remove old cache so fresh data is loaded.
🔹 Example: Clearing cache manually
Update user:
$user = User::find(1);
$user->name = "New Name";
$user->save();
// clear cache
Cache::forget("user_1");Delete user:
$user = User::find(1);
$user->delete();
// clear cache
Cache::forget("user_1");🔁 What happens after clearing cache?
- Cache is removed
- Next request hits database
- Fresh data is stored again
🧠 Cache Key Importance
To make this work properly, always use structured keys:
user_{$id}
user_{$id}_profile👉 This helps you delete only what is needed.
⚙️ What is booted() in Laravel?
The booted() method is used inside a Laravel Model to automatically run code when something happens to the model.
👉 It is often used for automatic cache clearing.
🔹 Example: Auto cache delete using booted()
Instead of manually writing Cache::forget() everywhere, you can centralize it in the model.
use Illuminate\Support\Facades\Cache;
class User extends Model
{
protected static function booted()
{
static::updated(function ($user) {
Cache::forget("user_{$user->id}");
});
static::deleted(function ($user) {
Cache::forget("user_{$user->id}");
});
}
}🔥 What happens here?
When user updates:
- Laravel automatically runs this code
- Old cache is deleted
When user deletes:
- Cache is also removed automatically
🧠 Why booted() is useful
Without booted() ❌
- You must manually clear cache everywhere
- Easy to forget → causes stale data
With booted() ✅
- Cache logic is centralized
- Automatically executed
- Cleaner and safer code
⚠️ Important Note
- Keep
booted()logic simple - For large applications, Laravel Observers are preferred
🏁 Final Summary
- Don’t cache frequently changing or critical data
- Always clear cache when data is updated or deleted
- Use
Cache::forget()for manual clearing - Use
booted()for automatic cache management
🚀 Final Thought
Caching is powerful, but only when used smartly. The goal is not to cache everything—but to cache the right things in the right way.
