Today we are going to discuss Laravel model observers tutorial with examples.
Laravel is a powerful PHP framework that has revolutionized web development with its simplicity and robustness. One of the features that makes Laravel stand out is its support for Model Observers.
Model Observers allow you to attach certain actions to specific events in your Eloquent models, making it easier to perform tasks like auditing, data manipulation, and notifications.
In this tutorial, we will explore the concept of Model Observers in Laravel 10 and demonstrate their usage with a practical example.
Before diving into this tutorial, you should have a basic understanding of Laravel and its Eloquent ORM. You should also have Laravel 10 installed on your system. If you haven’t done so, you can follow the official Laravel installation guide to set up your environment.
Model Observers are classes that listen for specific Eloquent events and respond to them with custom logic. These events include creating, updating, deleting, and restoring (soft deleting) model instances.
By defining an observer, you can decouple the logic related to these events from your models, leading to a cleaner and more maintainable codebase.
Below is a list of the Eloquent events that observers can listen to:
To create a Model Observer in Laravel 10, follow these steps:
php artisan make:observer
command. Replace ObserverName
with a meaningful name for your observer.php artisan make:observer ObserverName
app/Observers
directory. Inside the class, you will find various methods corresponding to the Eloquent events you can listen to. For instance, the created method will be triggered when a new model instance is created.namespace App\Observers; use App\Models\YourModel; class ObserverName { public function created(YourModel $model) { // Your logic here } // Add more event listeners as needed }
3. Registering the Observer: After defining your observer, you need to register it in the boot method of the AppServiceProvider
(if it doesn’t already exist). This will ensure that Laravel knows about your observer and automatically triggers the event listeners when the corresponding events occur.
namespace App\Providers; use Illuminate\Support\ServiceProvider; use App\Observers\ObserverName; use App\Models\YourModel; class AppServiceProvider extends ServiceProvider { public function boot() { YourModel::observe(ObserverName::class); } }
Let’s consider a practical example of using Model Observers to audit article edits in a blog application.
1. Create the Article Model: First, create an Eloquent model for the articles using the following command:
php artisan make:model Article -m
This command will generate the Article model along with a migration file to create the corresponding database table.
2. Add the necessary columns: In the migration file created for the articles table, add two additional columns: last_edited_by
(to store the user ID of the last editor) and last_edited_at
(to store the timestamp of the last edit). Run the migration to update the database.
3. Create the Observer: Now, create an observer called ArticleObserver
using the command mentioned earlier.
php artisan make:observer ArticleObserver
4. Define Event Listeners: In the ArticleObserver
class, define the updating event listener to capture article edits and update the last_edited_by
and last_edited_at
columns.
namespace App\Observers; use App\Models\Article; use Illuminate\Support\Facades\Auth; class ArticleObserver { public function updating(Article $article) { $article->last_edited_by = Auth::id(); $article->last_edited_at = now(); } }
5. Register the Observer: Open the AppServiceProvider
and register the ArticleObserver
in the boot method.
namespace App\Providers; use Illuminate\Support\ServiceProvider; use App\Observers\ArticleObserver; use App\Models\Article; class AppServiceProvider extends ServiceProvider { public function boot() { Article::observe(ArticleObserver::class); } }
With this setup, every time an article is updated, the updating method in the ArticleObserver
will be triggered, automatically updating the last_edited_by
and last_edited_at
columns in the database.
In this tutorial, we have explored the concept of Laravel 10 Model Observers and demonstrated their implementation with a practical example. Model Observers help you decouple the logic related to Eloquent events from your models, resulting in cleaner and more maintainable code. By using them, you can easily perform tasks such as auditing, data manipulation, and notifications in response to specific model events.
Today we are going to learn about managing multiple PHP versions on ubuntu with xampp.…
Let's understand about how to use coding to improve your website's SEO. In today’s computerized…
Let's understand the most important linux commands for web developers. Linux, as an open-source and…
Today we are going to discuss top 75+ Laravel interview questions asked by top MNCs.Laravel,…
Today we will discuss about the Mailtrap integration with laravel 10 .Sending and receiving emails…
Today we are going to integrate FCM (Firebase Cloud Messaging) push notifications with ionic application.Firebase…