DEV Community

Debajyoti Das
Debajyoti Das

Posted on

Observers in Laravel

Create laravel project

php artisan make:model Event --mcr //Create model, migration, controller, make controller as resource controller

php artisan make:observer EventObserver --m=Event

After running the abover command laravel will provide certain observer methods.

<?php

namespace App\Observers;

use App\Models\Event;

class EventObserver
{
    /**
     * Handle the User "created" event.
     *
     * @param  \App\Models\Event  $user
     * @return void
     */
    public function created(Event $event):void
    {
        //
    }

    /**
     * Handle the User "updated" event.
     *
     * @param  \App\Models\Event  $event
     * @return void
     */
    public function updated(Event $event):void
    {
        //
    }

    /**
     * Handle the User "deleted" event.
     *
     * @param  \App\Models\Event $event
     * @return void
     */
    public function deleted(Event $event):void
    {
        //
    }

    /**
     * Handle the User "restored" event.
     *
     * @param  \App\Models\Event $event
     * @return void
     */
    public function restored(Event $event):void
    {
        //
    }

    /**
     * Handle the User "forceDeleted" event.
     *
     * @param  \App\Models\Event $event
     * @return void
     */
    public function forceDeleted(Event $event):void
    {
        //
    }
}

Enter fullscreen mode Exit fullscreen mode

Complete list of methods given below:

  • retrieved
  • creating
  • created
  • updating
  • updated
  • saving
  • saved
  • deleting
  • deleted
  • trashed
  • forceDeleting
  • forceDeleted
  • restoring
  • restored
  • replicating

Go to app/Providers/EventServiceProvider an boot it:

use App\Models\Event;
use App\Observers\EventObserver;

/**
 * Register any events for your application.
 *
 * @return void
 */
public function boot()
{
    Event::observe(EventObserver::class);
}
Enter fullscreen mode Exit fullscreen mode

Now whenever for example Event::updateOrCreate() method is called, suppose we haven't passed an id, soon after the create operation happens the code will move to the Observer's created method, execute the block and come back and start executing the rest of the code.

For digging deeper into Observers, refer below docs:
https://laravel.com/docs/9.x/eloquent#observers
https://laravel.com/docs/9.x/eloquent#events

Top comments (0)