# Introducing Laravel Observers
Observers are used to group event listeners for a model. Observers classes method names refer to the Eloquent event you want to listen for. These methods receive the model as their only arguments. Laravel does not include a default directory for observers.
The model events that can be observed are spread across the model's CRUD and includes:
- Retrieved
- Creating
- Created
- Updating
- Updated
- Saving
- Saved
- Deleting
- Deleted
- Restoring
- Restored
The above events can be observed for every model in the Laravel Framework and business logic attached to it, you can also dispatch custom events from the observer and listen to it from other parts of your application.
To create an observer class, run this command:
php artisan make: observer <observerName>
replace observerName with the name of the model you are observing.
This will create a folder in your application's app directory called Observers and store the observer class.
<?php
namespace App\Observers;
class BankObserver
{
// an empty observer class
}
It is worthy to note that you can attach a model to an observer when creating the observer. Like this:
php artisan make:observer <observerName> -m=<ModelName>
By running this command, it will create the class with some method filled in by default.
<?php
namespace App\Observers;
use App\Task;
class Task
{
/**
* Handle the task "created" event.
*
* @param \App\Task $task
* @return void
*/
public function created(Task $task)
{
//
}
/**
* Handle the task "updated" event.
*
* @param \App\Task $task
* @return void
*/
public function updated(Task $task)
{
//
}
/**
* Handle the task "deleted" event.
*
* @param \App\Task $task
* @return void
*/
public function deleted(Task $task)
{
//
}
/**
* Handle the task "restored" event.
*
* @param \App\Task $task
* @return void
*/
public function restored(Task $task)
{
//
}
/**
* Handle the task "force deleted" event.
*
* @param \App\Task $task
* @return void
*/
public function forceDeleted(Task $task)
{
//
}
}
# Retrieved
This observer method is called when a model record is received from the database
Model::findOrFail($id); //this triggers the retrieved method in the observer class
# Creating
This observer method is called when a model record is in the process of creation and not yet stored into the database, this is before the id and the default timestamps are generated for the model. At this point you can dynamically check for and assign a default value to a missing column.
# Created
This observer method is called after a model record is created succesfully. If there is an error in the process of creation, say a missing column data, this method doesn't get called.
Model::create([]); //this triggers the creating method first, then created method in the observer class.
# Updating
This observer method is called when a model record is in the updating process, at this point, the updates has not yet been persisted to the database.
# Updated
This observer method is called after a model record is updated successfully. If there is an error in the process of updating, this method doesn't get called.
Model::update([]); //this triggers the creating method first, then created method in the observer class.
# Saving and saved
These model observer methods might seem a bit like a swiss army knife, it gets called before and after any event that requires persistence of data to the database, so if you're creating a new model record, the saving method runs first, then the creating method, then the created method and finally the saved method, the same routine applies when updating a model, saving, updating, updated, saved.
# Deleting
This observer method is called when a model record is in the deletion process, at this point, the record has not yet been deleted from the database and using its id to retrieve it from the database will return appropriate data.
# Deleted
This observer method is called after a model record is successfully deleted, at this point, the record has been deleted from the database.
Model::destroy($id);
# Restoring and Restored
These observer methods are called when a deleted model record is restored (using soft deleted implementation)
# Important things to note:
The updating and updated methods only run when the update changes a column of the model in the database, as such, if the update request does not effect a change, the updating and updated observers don't trigger, only the saving and saved methods get triggered.
When restoring a deleted record, series of methods gets triggered one after the other, retrieved, restoring, saving, updating, updated, saved then restored.
In any case where you want to make a model event without triggering any observer method, you can save it without observer events. An example of a method to use when creating a model without triggering any of the events:
public function saveQuietly(array $options = [])
{
return static::withoutEvents(function () use ($options) {
return $this->save($options);
});
}
Note: This method should be added in the respective model.
The last part is to bind the observer to a particular model. This can be done in the boot method of the AppServiceProvider
's class:
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
Model::observe(Observer::class);
}
Note: Model is the model to be observed and observer is the observer class