Laravel Basic | How to use Laravel Model Observers

Hello,

If you need to see the example of laravel observers example. We will use how to use laravel model observers. you can understand a concept of what is observers in laravel. this example will help you laravel model observers.

I will explain to you how to use the laravel model observers event, you can easily use it with laravel 6, laravel 7, laravel 8, and laravel 9 projects.

Laravel Observers are used to group event listeners for a model eloquent. Laravel Observers will listener event for a model eloquent method like create, update and delete.

I will give you a very simple definition and use of laravel observers is, when you need to generate slug or auto-generate unique id or something like logic add before or after creating record then observers will help you. I will give you bellow events provided by observers and simple examples below:

Eloquent Hook

  • Retrieved: after a record has been retrieved.
  • Creating: before a record has been created.
  • Created: after a record has been created.
  • Updating: before a record is updated.
  • Updated: after a record has been updated.
  • Saving: before a record is saved (either created or updated).
  • Saved: after a record has been saved (either created or updated).
  • Deleting: before a record is deleted or soft-deleted.
  • Deleted: after a record has been deleted or soft-deleted.
  • Restoring: before a soft-deleted record is going to be restored.
  • Restored: after a soft-deleted record has been restored.

Example:

Now here we will see a simple example, I have one product model and it has a name, slug, price, and unique_id column. so I need to create one record with the name and price only. but when it’s created I need to generate slug from name and auto-generate unique_id.

so let’s see how to create an observers class and how it will work:

app/Models/Product.php

Create observers class for Product. So, create bellow command:

app/Observers/ProductObserver.php

Register Observers class on the provider.

app/Providers/EventServiceProvider.php

Create Demo Route:

routes/web.php

Create Controller Route:

app/Http/Controllers/ProductController.php

now you can run the project and see.

it will create a record as like bellow:

Laravel Basic | How to use Laravel Model Observers

I hope it can help you…

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store