0
0
Laravelframework~30 mins

Model events and observers in Laravel - Mini Project: Build & Apply

Choose your learning style9 modes available
Model Events and Observers in Laravel
📖 Scenario: You are building a Laravel application to manage a list of books. You want to automatically log a message whenever a book is created in the database.
🎯 Goal: Create a Laravel model called Book and an observer called BookObserver. Set up the observer to listen for the created event on the Book model and log a message when a new book is added.
📋 What You'll Learn
Create a Book model
Create a BookObserver class
Register the observer in the AppServiceProvider
Implement the created method in the observer to log a message
💡 Why This Matters
🌍 Real World
Model events and observers help automate tasks like logging, notifications, or data cleanup when database records change.
💼 Career
Understanding Laravel model events and observers is essential for backend developers to write clean, maintainable, and reactive applications.
Progress0 / 4 steps
1
Create the Book model
Create a Laravel model called Book using the php artisan make:model Book command or by creating a class Book that extends Illuminate\Database\Eloquent\Model.
Laravel
Need a hint?

The model class should be in the App\Models namespace and extend Model.

2
Create the BookObserver class
Create an observer class called BookObserver in the App\Observers namespace. Add a public method created that accepts a Book instance as a parameter.
Laravel
Need a hint?

The observer class should have a created method that receives a Book object and logs a message.

3
Register the observer in AppServiceProvider
In the App\Providers\AppServiceProvider class, import Book and BookObserver. In the boot method, register the observer by calling Book::observe(BookObserver::class);.
Laravel
Need a hint?

Make sure to import both Book and BookObserver classes and call observe inside the boot method.

4
Test the observer by creating a Book instance
Add code to create a new Book instance with title set to 'Laravel Basics' and save it to the database. This will trigger the created event and log the message.
Laravel
Need a hint?

Create a new Book object, set the title property, and call save() to trigger the observer.