Detecting Attribute Changes in Laravel Observers
When building a system that tracks user activity, you often need to know exactly what changed during an update operation. A common scenario involves auditing whether a user's email address was modified. While the Eloquent updated event fires whenever any attribute changes, it does not specify which ones. To detect specific modifications like an email change, you must leverage the updating event instead.
The updating event occurs before the database write is executed but after the model has been mutated. This timing is critical because it allows you to inspect the current state of the model against its original state without triggering side effects prematurely. In your observer, you can access two key properties: $user->getOriginal() and $user->isDirty().
The getOriginal() method returns the values of the attributes as they existed when the model was instantiated or last saved. By comparing the current email value against this original snapshot, you can determine if a change is pending. The logic is straightforward: cast both values to strings to handle potential null differences gracefully, then compare them directly.
use App\User;
class UserObserver
{
public function updating(User $user)
{
// Check if the 'email' column has actually changed
if (
$user->getOriginal('email') !==
(string) $user->email
) {
// Handle the email change logic here
// For example, logging to an audit table or sending a verification email
Log::info("User email is about to be updated", [
'old_email' => $user->getOriginal('email'),
'new_email' => $user->email,
]);
}
}
}
It is important to understand why we cast the new email value to a string. In Eloquent, boolean false evaluates as empty when compared to null in certain contexts, and empty strings can behave unexpectedly if not normalized. Casting ensures that a falsey input (like an empty string) is treated consistently against an original null or empty state. This prevents false positives where the logic might incorrectly trigger on type mismatches rather than actual value changes.
Alternatively, you can use the isDirty() method combined with specific attribute checking. While isDirty('email') is a concise way to check if an attribute is marked as changed, it relies on Eloquent's internal tracking of dirty attributes. The approach using getOriginal is often preferred for explicit value comparison because it gives you direct access to the old and new values within your conditional block, making it easier to include both in log entries or database audit records.
One potential pitfall involves mass assignment protection and fillable arrays. If your application logic sets a default email before calling update, the change might not be considered "dirty" by Eloquent if the value hasn't technically changed from the original instance state. However, in standard update scenarios where a new value is provided, the dirty tracking works as expected.
Another consideration is performance. Accessing getOriginal() involves reading from an internal array maintained by Eloquent. While this operation is negligible for most applications, it adds a tiny overhead compared to skipping the check entirely. If you are updating thousands of records in a loop without needing to track email changes specifically, consider using a single query with conditional logic or batching updates to minimize observer executions.
For more complex auditing needs where you need to persist every change regardless of the attribute, implementing a dedicated audit table that gets updated within the observer is a robust pattern. This keeps your main models clean and separates business logic from data structure concerns. If you require further guidance on advanced Eloquent patterns or customizing Laravel applications for enterprise use, resources like https://laravelcompany.com offer in-depth documentation and community support.