Introduction to the booted method in Eloquent
In Laravel's Eloquent ORM, the booted method is called when an Eloquent model is instantiated. This method provides a convenient place to register event listeners or perform other setup tasks.
By using the booted method, you can keep your model logic organized and easy to maintain. In this post, we'll explore how to use the booted method to listen for CRUD events and reset cache when creating or updating a model.
Lets understand it using example:
Suppose you have a Laravel application with a User
model that is frequently accessed and updated. To speed up queries and reduce database load, you decide to cache user data using Laravel's Cache façade.
To cache user data, you'll need to store it using a unique cache key. You could use the user's ID as the cache key, but what happens when the user's data changes? You'll need to update the cache key every time the user is updated to ensure that the cache is not stale.
To automate this process, you can use the booted method to listen for the creating
and updating
events on the User
model, and reset the cache
for the user being created or updated.
Registering event listeners
To listen for CRUD events, you can register event listeners using the creating
, created
, updating
, updated
, saving
, saved
, deleting
, and deleted
methods on the model's static boot method.
In this example, we'll use the creating
and updating
events to reset cache for the user being created or updated.
Here's how you can define event listeners in the boot method of the User model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;
class User extends Model
{
protected static function booted()
{
static::creating(function ($user) {
Cache::forget('user_' . $user->id);
});
static::updating(function ($user) {
Cache::forget('user_' . $user->id);
});
}
}
Resetting cache
To reset cache for a model, you can use Laravel's Cache facade. The Cache facade provides a simple API for storing and retrieving data from a variety of cache backends.
For example, to cache a user model by their ID, you can use the remember method of the Cache façade:
$userId = 1;
$user = Cache::remember('user_' . $userId, $minutes, function () use ($userId) {
return User::find($userId);
});
In the above code, the remember method caches the user model with ID 1 for the specified number of minutes. If the cache is not already set, the closure passed to remember is called to retrieve the data and cache it.
To reset cache for a user when they are created or updated, we use the forget method
Conclusion
In this post, we've explored how to use the booted method in Eloquent models to listen for CRUD events and reset cache when creating or updating a model. By using event listeners and the Cache façade, you can keep your model logic organized and easy to maintain.
Top comments (0)