Hello guys, Welcome you to the Channel. Today in this video we will learn about Laravel
Observers. First, let’s look at some Eloquent models
events. Model events allow you to execute code into
some points in a model’s life-cycle and there are 11 events in the model’s life-cycle. These are: model retrieved, creating, created,
updating, updated, saving, saved, deleting, deleted, restoring, restored. These events are self-explanatory like when
these events will fire. For example, this retrieved event will fire
when an existing model retrieved from the database. When the model saved for the first time, then
creating and created events will fire. If a model already existed in the database
and we modify its data and call the save method to save it in the database, then updating
/ updated events will fire. However, in both cases, the saved/saving events
will be fire. And On delete model this deleting and deleted
event will fire and when the delete model is restored then this restoring and restored
event will fire. Laravel provides three ways to use these events. One is the event listener, the 2nd way is
to override the boot function of the model itself and the 3rd way is the observers. Let’s see how we can implement these three
ways in Laravel. Before moving ahead a quick reminder, if you
are new to this channel, hit the red subscriber button and press bell icon. So, you could never miss our upcoming videos. Now let’s start with the event listener. So, first let's delete this. Let’s say in the user model, we want to
fire an event when a user created. Maybe for sending a welcome email when a user
created. So, here we define protected $dispatchesEvents
property. It is an array, that maps model’s life-cycle
events like created, updated to the event classes. In our case, here I will say,
created is equal to UserCreated::class. Now here we are saying when the user created,
fire this event. We don’t have this event class. So, let’s create this. php artisan make:event UserCreated
Event created successfully. App, events, here is our UserCreated event. Here in this __construct method, it will accept
the User model $user. Next, here I will say,
$this->user = $user; And Right here let's define public $user. Now to handle this event we can also create
a listener for this. So, in terminal here we say,
php artisan make:listener UserCreatedListener -e UserCreated
Listener created successfully. In the editor, App Listeners, here is UserCreatedListener. In this handle method, we can execute any
logic we need for the application, for example, sending a welcome email to the user when it
is created. Now let's dump the event to check if it hits
this event listener on create a user. So, here I will say "from UserCreatedListener"
and here I will say $event->user. Here is event is this UserCreated event class,
and this user is this public user. Our next step is to register this event listeners
in the EventService provider class. So, App Providers EventServiceProvider. Right here we say,
UserCreated::class is equal to listeners array, That is UserCreatedListener::class. And Make sure to import the classes here. This is all we need. Now let's see if it works. And we know when we register a user, then
a user is created in the database. At that point, we should see this dump. So, let's see this in the browser. Now let's register a user. Harish
harish@example.com password. Register. Class App\UserCreated not found. We forgot to import this class here. Register again. John,
john@example.com password. Register. And here we get this,
from UserCreatedListener, and this is the user object that is created. Similarly, we can add more, event listeners
for other model life cycle events, like updated => UserUpdated::class. I only use this way, when I am working with
real-time applications because this event class allows to broadcast the data. For other cases, I use Overriding the Models
Boot method or observers. Next, let's see how we can use Model boot
method. So, first, let's delete this. Now, Right here, I will create, public static function boot, and next, parent::boot();
Now right here I will say, static::created(). This created is the model event. If you want to hook your code when the model
is updated then you can say, static::updated, similarly, if you want to
execute your code when the model deleted then you can say static::deleted, and so on. For now, here I will say created, and we pass
a closure function. This closure function will accept the model,
In here that is this user model. Here I will say, $user. Now in this function, we can write whatever
the logic needs to execute when a user is created. For now, I am going to dump this user model
and we see in the browser if works when user is created. so, here we say, "from boot method", and here
we say $user. Now let's see this in the browser. Register another,
Adam adam@example.com
password And register, Now here we get this dump data from boot method,
and this is the created user object. Similarly, we can add more events like this. So, Sometimes these may get bigger and you
may want to move these events in the dedicated class. So, here the use of observes comes in. Observers allow you to group all of the event
into single class. Now let's delete this and create an Observer. Now in the terminal, we say, php artisan make:observer UseObserver --model=User In the editor,
App Observers here is the UserObserver Class. Laravel has generated some boilerplate for
us. Here, we only need this created method. So, let's delete rest of the methods. And here in this method I
will dump: "from UserObserver", $user. Let's see if it works. Let's register again. Kumar,
kumar@example.com password. It did not work. Actually we forget to register this UserObserver
in the service provider. So, let's navigate to events service provider. Right here in boot method we say,
User::observe(UserObserver::class); Make sure to import these classes. Now Let's see this in
the browser again Smith
smith@example.com password
and register, Now we get this dump from UserObserver. Let's see one more example of the Observer. I believe you will definitely want to use
that in your real life project. So, let's see. Here you can see, I have created Category
model. And In the Database migration, Category table,
I have added string name column. I have also created CategoryFactory for generating
some demo categories. Next, in the resources > views > layouts ? _nav.blade.php. Here I have created this dropdown for categories. This is the foreach loop for all categories,
and this is the link for the single category. And I have included this nav partial in this
app.blade.php, right here. Here this categories variable is passed this
nav blade file from AppServiceProvider using this View::composer. Here the blade layouts._nav. Here we fetched all categories and passed
to the view right here. And in web routes, I have created this route,
to show single category. Now let's see this in the browser. Here is the dropdown list of categories. And if I click on this, it navigates to the
category page. Now, here in the debug bar,
In case you don't know what is debug bar and how to install it in Laravel application,
then I recommend you to watch the video on "Optimize Laravel Eloquent Queries with Eager
Loading". you can find the link of it in the video description. Here you can see, Two SQL query. If I navigate to other pages, you can see
the one common query. And here we can remove this query If we store
all categories in the cache. Let's see. In AppServiceProvider,
Now to store all categories in the cache, here I will say,
Cache rememberForever and the cache key name let's say categories, here we return all categories. Now let's see in the browser, refresh. For the first time, we will see the query,
because categories were not in cache. So, it will execute the query and fetch the
results and store the data in the cache. So, if I refresh again, and this time you
will see no query in the debug bar. Great, it is working nice. All categories are working. We can navigate to each category. But here is the big problem. If I update any category name and refresh
it again, it will not affect here, because these category list is coming from the cache. Let's see. In the terminal, php artisan tinker. Here I will fetch the first category,
So, $category is equal to App\Category::first();
Next, $category->name is equal let's say "Laravel";
$category->save(); Now the category
is updated. Come back to the browser, refresh. And it is not reflected here. Similarly, If I add a new category or delete
any existing category, It will not be reflected here because that category list fetched from
cache. So, to fix this, we have to clear the categories
cache, when a new category created, or category updated, or an existing category deleted. For that, I will create an observer for Category
Model. So, let's create this,
In terminal, php artisan make:observer CategoryObserver
--model=Category Observer created successfully. Next, in CategoryObserver, Here we have some
boilerplate. Here we need created, updated and delete method. Others we don't need, So, let's delete this. Now right here I will create a protected method
clearCache(), In this function, I will say,
Cache::forget() And here we pass the cache key that we want to delete. If we see in AppServiceProvider, key name
is categories. So, let's paste this here. Now we call this function, in all event methods. Here we say, $this->clearCache(); Paste here, Next, I will register this observer in EventServiceProvider. So, EventServiceProvider. And here we say,
Category::observe(CategoryObserver::class); Now in browser, refresh. We still did not see any effect, because still
fetched from cache. But this time, If I update the category, it
will remove the categories cache and here it will show fresh data. So, in the terminal. php artisan tinker. I will fetch the first category. And we say,
$category->name is equal to, let's say this time "PHP";
And $category->save(); Now category is updated. Head to browser, Refresh. And this time it is reflected right here. In debug bar you can see, this SQL query executed
because it did not find the cache. Now it is cached, So, if I refresh again,
and here you will see no query is executed. Similarly, If I delete a category, Here now we can see only 4 categories. And this Sql query executed again. Similarly, If I create a new category, we
will see the same result. Let's see. factory(App\Category::class)->create();
And this new category created. Let's see. Here it is listed. And this sql query executed. Now everytime, when we update category, or
add a new category or delete an existing category. It will clear the cache everytime, and we
will get fresh categories data. This is all in this tutorial, If you like
the video Hit the like button, Share this video and don't forget to subscribe us. See you in the next video.