Good content takes time and effort to come up with.

Please consider supporting us by just disabling your AD BLOCKER and reloading this page again.







Observers In Laravel | StackCoder


Observers In Laravel


04th August 2020 3 mins read
Share On     Share On WhatsApp     Share On LinkedIn


Sometimes, we may have a requirement to add or modify some data before creating some record or after creating a record, before updating a record or after updating a record and many more scenarios like fetching data, deleting, restoring data.


We will cover the following topics in this article


  1. Why Laravel Observers? Different Types Of Observers
  2. Creating Observers
  3. Registering Observers
  4. Example Of Using Observers

1) Why Laravel Observers? Different Types Of Observers


For example: If you want to keep a track of which user added the record or which user updated a record then Observers are the best.


Observers are simple event listeners on your model which can be used to DRY up your code.


The following are the different types of observers.


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 ie when the model is created or updated.

saved - after a record has been saved ie when the model is 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.


2) Creating Observers (app/Observers)


Creating observers in Laravel is very simple. Just run the following command


php artisan make:observer -m Models/Customer CustomerObserver


You need to pass the following parameters:


i. Model Name - Models/Customer (My model name is Customer which resides inside App/Models folder)


ii. Observer Name - CustomerObserver (Any name as per your requirement)


CustomerObserver gets created in app/Observers. Which will look like the following


NOTE - Only the model will be passed as a parameter for all the Observers functions.


app/Observers/CustomerObserver.php

<?php

namespace App\Observers;

use App\Models\Customer;

class CustomerObserver
{
    public function created(Customer $customer)
    {
        //
    }

    public function updated(Customer $customer)
    {
        //
    }

    public function deleted(Customer $customer)
    {
        //
    }

    public function restored(Customer $customer)
    {
        //
    }
    
    public function forceDeleted(Customer $customer)
    {
        //
    }
}


Observe carefully here the following methods are not created by default. So we need to explicitly create as per our needs. Which I will show in 4)


creating, updating, deleting, restoring


3) Registering Observers (AppServiceProvider.php)


Once we create observer we need to tell Laravel about it. We can tell by registering the observers in AppServiceProvider


app/Providers/AppServiceProvider.php

<?php

namespace App\Providers;

use App\Models\Customer;
use App\Models\CustomerAddress;
use App\Observers\CustomerObserver;
use Illuminate\Support\ServiceProvider;
use App\Observers\CustomerAddressObserver;

class AppServiceProvider extends ServiceProvider
{
    public function register()
    {
        //
    }

    public function boot()
    {
        Customer::observe(CustomerObserver::class);
        CustomerAddress::observe(CustomerAddressObserver::class);
    }
}

4) Examples


In the Customer model when someone creates any new customer or updates customer, I need to know who had created the customer and who had updated the customer. We can achieve it by using creating, updating Observers like the following


app/Observers/CustomerObserver.php

<?php

namespace App\Observers;

use App\Models\Customer;

class CustomerObserver
{
    public function creating(Customer $customer)
    {
        $customer->added_by_id = session()->get('user')->id;
    }

    public function updating(Customer $customer)
    {
        $customer->updated_by_id = session()->get('user')->id;
    }
}


Similarly, you can add any code as per your needs.


Conclusion


If you are new to AMP then don't forget to check out the following articles




Author Image
AUTHOR

Channaveer Hakari

I am a full-stack developer working at WifiDabba India Pvt Ltd. I started this blog so that I can share my knowledge and enhance my skills with constant learning.

Never stop learning. If you stop learning, you stop growing