Laravel Model Hooks: Beyond afterSave and beforeSave
You are likely familiar with the concept of lifecycle hooks in other frameworks or ORM ecosystems, where methods like beforeSave() or afterSave() seem like a natural fit for executing logic around data persistence. In Laravel, however, the approach is slightly different due to its reliance on events rather than direct method injection into the model class itself. While you might initially search for built-in beforeSave or afterSave methods within the Eloquent model, these do not exist as standard API features in the core framework.
Instead, Laravel provides a robust event system that offers the same functionality with significantly more flexibility. When a model is saved via $model->save(), Laravel automatically fires specific events before the database query executes and after it completes successfully. The primary events you need to know are eloquent.booting (before any save), eloquent.saving (right before the SQL query runs), and eloquent.saved (after a successful save).
If your goal is to execute code immediately before or after a specific model instance changes, you should utilize these events. You can listen to them globally in an event listener or locally within the model class using the $dispatchAfterSave() helper or by defining protected methods that are called internally. However, the most idiomatic Laravel approach involves registering listeners in your AppServiceProvider.
Here is how you might register a listener for the eloquent.saving event to handle validation logic or audit logging:
use Illuminate\Support\Facades\Event;
use App\Events\UserAboutToBeSaved;
public function register()
{
Event::listen(
\Illuminate\Database\Eloquent\Events\ModelSaving::class,
function (\Illuminate\Database\Eloquent\Model $model) {
// Logic runs right before the SQL query executes
if ($model->isDirty('email')) {
$model->email_was = $model->email;
}
}
);
}
Alternatively, you can define these hooks directly within the model class using protected methods. This approach keeps the logic encapsulated with the entity but requires defining the method signature to match Laravel's internal expectations or using a trait like HasEvents. A common pattern seen in many applications is adding a saving and saved method directly to the model:
class User extends Model
{
protected $fillable = ['name', 'email'];
public function saving()
{
// This method is called before save()
// You can modify attributes or throw exceptions here
if ($this->email && !filter_var($this->email, FILTER_VALIDATE_EMAIL)) {
throw new \Exception('Invalid email address');
}
}
public function saved()
{
// This method is called after a successful save
// Useful for logging or updating related records
$this->touchTimestamp();
}
}
It is crucial to understand the timing and limitations of these hooks. The eloquent.saving event fires before any database interaction occurs, making it ideal for data sanitization or throwing validation exceptions that abort the save operation. Conversely, the eloquent.saved event only triggers if the transaction was committed successfully. If an exception is thrown during the save process, the saved event will never fire.
A common pitfall developers face is attempting to perform expensive operations inside these hooks without considering performance implications. Since these methods can be called frequently depending on your application's write volume, ensure that any logic inside them is lightweight. For complex operations like sending emails or writing to external APIs, consider deferring the action to a queue job triggered within the saved hook instead of executing it synchronously.
While there are no direct equivalents to beforeSave() and afterSave() in the sense of standard method names that Laravel auto-wires without definition, the event system fills this role effectively. If you require more granular control or need to handle specific scenarios that events might not cover, you can always define your own custom events using the Event facade. This allows you to decouple business logic from the persistence layer entirely, adhering to Laravel's separation of concerns principles.
For deeper dives into event handling patterns and best practices for maintaining clean architecture in Laravel applications, resources like https://laravelcompany.com often provide detailed guides that complement the official documentation.