Demystifying Laravel Model Listeners and Observers for Beginners

Demystifying Laravel Model Listeners and Observers for Beginners

We’ll be looking deep into how we can easily listen to model changes and update those changes in respective models. What are the Laravel Events? What are Laravel Observers? How can you create an Event in Laravel? How can you create a Model Observer in Laravel? Difference between Laravel Events and Observers. Skipping or Ignoring Laravel Model Events. Mapping all the events of applications within EventServiceProvider. Registering Lifecycle methods with Event Class within the models

Hey in this post on Demystifying Laravel Model Listeners and Observers for Beginners we’ll be looking deep into how we can easily listen to model changes and update those changes in respective models.

We’ll be using Post and Comments as an example and guide you within the various steps that come along the way.

Table of Contents

  • What are the Laravel Events?
  • How can you create an Event in Laravel
  • Mapping all the events of applications within EventServiceProvider
  • Registering Lifecycle methods with Event Class within the models
  • Shortner way to achieve the same goal
  • What are Laravel Observers?
  • How can you create a Model Observer in Laravel
  • Skipping or Ignoring Laravel Model Events
  • Difference between Laravel Events and Observers
  • Conclusion

What are the Laravel Events?

The Laravel Eloquent Events are triggered whenever a lifecycle of a model is called.

Some of the lifecycle methods are: retrieved, creating, created, updating, updated, saving, saved, deleting, deleted, restoring, restored, replicating. These are very useful when have to manage a large number of relationships that belong to many models and will greatly reduce the code size as the logic is managed by event and listener classes.

How can you create an Event in Laravel

There are many ways of creating Event and Listeners and we’ll be discussing in-detail as per the information provided by Laravel Documentation on Events.

For this, we have considered using creating Posts as an example so the PostModel contains fields such as post_id, name, slug, description.

Whenever a new post is created we would like Laravel to automatically convert the name into a slug only when a new post gets created.

So let’s start by creating a model for the post table.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class PostModel extends Model
{
    use HasFactory;

    protected $table = 'posts'; 
    protected $primaryKey = 'post_id'; 
    protected $fillable = ['name', 'slug', 'description' ];
    protected $dates = ['deleted_at']; 

    protected $with = [];
    protected $appends = [ ];
    protected $morphClass = "posts";

}

And the next step is to create an Event for PostModel. So type the below command into the terminal.

php artisan make:event PostEvent

Inside PostEvent:

<?php

namespace App\Events;

use App\Models\PostModel;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class PostEvent
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    /**
     * Create a new event instance.
     *
     * @return void
     */

    public $post;

    public function __construct( PostModel $post )
    {
        $this->post = $post;
    }

    /**
     * Get the channels the event should broadcast on.
     *
     * @return \Illuminate\Broadcasting\Channel|array
     */
    public function broadcastOn()
    {
        return new PrivateChannel('channel-name');
    }
}

And next create a respective listner for this event i.e PostCreated listener.

php artisan make:listener PostCreated

Inside PostEvent listener:

<?php

namespace App\Listeners;

use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;

class PostCreated
{ 
    /**
        * Create the event listener.
        *
        * @return void
        */
    public function __construct()
    {

    }

    /**
        * Handle the event.
        *
        * @param  object  $event
        * @return void
        */
    public function handle($event)
    {
        $post = $event->post;

        $post->slug = preg_replace( '/[^A-Za-z0-9]/', '-', strtolower( $post->name ) );
        $post->save();
    }
}

Mapping all the events of applications within EventServiceProvider

In EventServiceProvider all the events of the application will be mapped with their respective listeners. From here it is how Laravel gets to know which are the registered events.

So we should also add PostEvent and PostCreated listener in app\Providers\EventServiceProvider.php

protected $listen = [
    PostEvent::class => [
        PostCreated::class,
    ],
];

Registering Lifecycle methods with Event Class within the models

Now both the event and listener are ready so the next step is to associate the event with the model lifecycle hooks. Below I have shown how to do that with an example.

In Model

protected $dispatchesEvents = [
    'lifecycle-hook-name' => 'and here goes event class',
];

Caution: More of the people get it wrong they add the listener insisted on event. And you don’t do that mistake.

So we have to add dispatchesEvents property into PostModel.

<?php

namespace App\Models;

use App\Events\PostEvent;
use App\Listeners\PostCreated;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class PostModel extends Model
{
    use HasFactory;

    protected $table = 'posts'; 
    protected $primaryKey = 'post_id'; 
    protected $fillable = ['name', 'slug', 'description' ];
    protected $dates = ['deleted_at']; 

    protected $with = [];
    protected $appends = [ ];
    protected $morphClass = "posts";

    protected $dispatchesEvents = [
        'created' => PostEvent::class, // Event
    ];
}

The PostEvent is called after the created lifecycle is triggered. And this event, in turn, calls PostCreated listeners.

laravel php web-development programming developer

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

PHP Web Application Development Company

As a top **PHP Web Application Development Company in USA**[https://www.dataeximit.com/php-development-services/](https://www.dataeximit.com/php-development-services/ "https://www.dataeximit.com/php-development-services/"), we at Data EximIT have...

PHP Website Development

Skenix Infotech is a leading PHP Web Development Company that helps companies get results with industry best practices. Get affordable PHP Development Services.

Laravel Development Company

Skenix Infotech is a top Laravel Website Development Company with Expert Laravel Developers that provides robust Laravel Development Services at fair costs.

Hire Dedicated PHP Developer

Looking to hire affordable yet experienced PHP developers? **[Hire Dedicated PHP Developer](https://hourlydeveloper.io/hire-dedicated-php-developer/ "Hire Dedicated PHP Developer")**, who can convert your idea to reality, within the stipulated...

Hire PHP Developer

Looking to develop a PHP based website from scratch or revamp your existing website? **[HourlyDeveloper.io](https://hourlydeveloper.io/ "HourlyDeveloper.io")** has always been an industry leader for companies and business owners looking to hire...