How to Use Laravel Observers to Improve Your Application

How to Use Laravel Observers to Improve Your Application

A Laravel observer is a class that listens for events that occur on a model. Events are triggered when a model is being created, updated, deleted, or restored. Observers can be used to perform tasks such as sending emails, updating other models, or logging changes.

How to create a Laravel observer

To create a Laravel observer, you can use the make:observer Artisan command. For example, to create an observer for the User model, you would run the following command:

php artisan make:observer UserObserver

This will create a new observer class called UserObserver in the app/Observers directory. The observer class will have methods for each of the events that can occur on the User model. For example, the created method will be called when a new User record is created.

How to register a Laravel observer

To register a Laravel observer, you need to add it to the AppServiceProvider class. In the boot method, you need to call the registerObservers method on the EventServiceProvider class. The registerObservers method takes an array of observer classes as its argument. For example, to register the UserObserver class, you would add the following code to the AppServiceProvider class:

public function boot(EventServiceProvider $events)
{
  $events->registerObservers([
      \App\Observers\UserObserver::class,
  ]);
}


What are the benefits of using Laravel observers?

There are several benefits to using Laravel observers.

  • First, observers can help you to keep your code DRY (Don't Repeat Yourself). If you need to perform the same task before a model is created, when it is created, updated, deleted, or restored, you can use an observer to do it once instead of repeating the code in multiple places.
  • Second, observers can help you to make your code more modular. You can create separate observers for different tasks, and then register those observers as needed. This makes your code easier to understand and maintain.
  • Third, observers can help you to improve the performance of your application. If you need to perform a task when a model is created, updated, deleted, or restored, you can use an observer to do it in the background. This will prevent your application from blocking while the task is being performed.
Observer Methods
  • Creating: The creating method is called before a new model record is created. This method can be used to validate the data before it is saved to the database. 
  • Created: The created method is called after a new model record is created. This method can be used to perform any tasks that need to be done after the record is created. For example, the following code would send an email to the user confirming that their account has been created:
public function created(User $user)
{
  Mail::to($user->email)->send(new UserCreatedMail($user));
}
  • Updating: The updating method is called before a model record is updated. This method can be used to validate the data before it is saved to the database. For example, the following code would check to make sure that the name field has not been changed:
public function updating(User $user)
{
  if ($user->name !== $user->getOriginal('name')) {
      throw new \Exception('The name field cannot be changed.');
  }
}
  • Updated: The updated method is called after a model record is updated. This method can be used to perform any tasks that need to be done after the record is updated. For example, the following code would send an email to the user confirming that their account has been updated:
public function updated(User $user)
{
  Mail::to($user->email)->send(new UserUpdatedMail($user));
}
  • Deleting: The deleting method is called before a model record is deleted. This method can be used to prevent the record from being deleted. For example, the following code would check to see if the user has any orders before deleting their account:
  • Deleted: The deleted method is called after a model record is deleted. This method can be used to perform any tasks that need to be done after the record is deleted. For example, the following code would remove the user from all of the groups that they are a member of:
public function deleted(User $user)
{
  $user->groups()->detach();
}


Conclusion

Laravel observers are a powerful feature that can help you to improve the organization, performance, and maintainability of your application. If you are not already using observers, I encourage you to give them a try.

Enjoy this article ? drop a comment below and add your own contribution.

Maye Jacob

Jacob Olorunmaye

Verified Expert
Passionate Backend Developer | Expert in PHP, Laravel, JavaScript, and Golang 🚀 | Crafting seamless, scalable solutions for the digital era

Leave a Reply

Your email address will not be published. Required fields are marked *