Accessing Previous Attribute Values in Eloquent Events
When handling saving or updating events in an Eloquent model, a common requirement is to detect changes and execute logic based on what actually modified. The standard approach often seen in tutorials involves comparing the current attribute against an undefined "old" property. This pattern fails because Eloquent does not automatically expose historical data within the event callback scope using a magic ->old accessor.
To access the previous state of attributes, you must explicitly retrieve the original model instance before the mutation occurs. Eloquent provides the $original property on the model instance during these events. This property holds a snapshot of the model's state as it existed prior to the current save operation. It effectively answers the question: "What did this record look like before we touched it?"
The mechanism relies on how Eloquent tracks changes internally. When you access $model->original['username'], you are pulling from an array that maps attribute names to their values at the moment the model was instantiated or last saved successfully. This is distinct from $model->getAttributes(), which returns the current state including any queued mutations.
Here is a practical implementation using the updating event:
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
protected $fillable = ['username', 'email'];
public function boot()
{
$this->saving(function ($user) {
// Access the original username from the snapshot
$oldUsername = $user->original['username'] ?? null;
// Get the current queued value
$currentUsername = $user->getAttribute('username');
if ($oldUsername !== $currentUsername) {
// Execute logic only when the username actually changes
log("Username changed from {$oldUsername} to {$currentUsername}");
// Trigger external service or audit trail here
doSomething();
}
});
}
}
In this example, accessing $user->original is safe even if the attribute hasn't been set before; using the null coalescing operator (??) ensures you don't accidentally treat a missing key as an empty string. The comparison determines if the mutation involves a real change to the database row or just a validation reset.
Handling Mass Assignment and Scope
A critical pitfall arises when dealing with mass-assignment protection or scopes that modify attributes before the save event fires. If you use $user->original['username'], you are comparing against the state after the model was hydrated from the database but before the specific mutation queued in the current request.
If your application relies on a separate "old" model instance (e.g., stored in a cache or fetched manually), comparing that external instance to the current one introduces race conditions and unnecessary database queries. The $original property is designed specifically for this event context, ensuring a direct memory comparison between the pre-mutation state and the queued state.
When updating Might Not Be Enough
While the updating event fires when a model is about to be updated, it does not fire if no attributes are actually changing or if the update operation is aborted by validation rules before the save hook executes. If your logic depends on detecting any attempt to modify a field, even one that fails validation, the saving event is more robust. However, saving includes both insert and update operations. To isolate updates specifically while still accessing the original state, you must check $model->isDirty() or inspect the $changes array alongside the $original property.
if ($this->isDirty('username')) {
$oldValue = $this->original['username'];
// Proceed with logic
}
This pattern ensures your event handlers remain performant, executing complex logic only when necessary, and avoids unintended side effects on fields that were not intended to be modified.