Laravel 10 How To Work with Model Events And Listeners

Reading Time: 11 minutes
462 Views

Inside this article we will see the concept of Laravel 10 How To Work with Model Events And Listeners. Article contains classified information about What are Model Events And Listeners and how to handle in laravel application.

In Laravel, Model Events and Listeners are a way to hook into the lifecycle of an Eloquent model and perform some action when certain events occur.

Model events are triggered when a specific action is performed on an Eloquent model instance, such as creating, updating, or deleting a record.

Read More: Laravel 10 Export MySQL Table Data into CSV File Tutorial

Let’s get started.

Laravel Installation

Open terminal and run this command to create a laravel project.

composer create-project laravel/laravel myblog

It will create a project folder with name myblog inside your local system.

To start the development server of laravel –

php artisan serve

URL: http://127.0.0.1:8000

Assuming laravel already installed inside your system.

What are Model Events in Laravel?

A Model in Laravel application provides an abstraction for working with a database table with a high-level API. Among these APIs, events are which are fired when actions are performed on the model.

Models events in simple terms are hooks of a model’s life cycle which you can use to easily run code when database records are saved, updated or deleted.

Events receive the instance of the model which is being saved, updated or deleted.

Here are the following events which we can use with laravel model –

  • creating and created: Fires before and after records have been created.
  • updating and updated: Fires before and after records are updated.
  • saving and saved: Fires before and after records are saved (i.e created or updated).
  • deleting and deleted: Fires before and after records are deleted or soft-deleted.
  • restoring and restored: Fires before and after soft-deleted records are restored.
  • retrieved: Fires after records have been retrieved.

Let’s consider an example to understand the things.

Read More: How To Upload File Using Livewire in Laravel 10 Tutorial

Working with Model Events

Suppose, we have a CRUD application for devices in which we are performing –

  • Create & Save device data into database table
  • Update Device data
  • List Device rows
  • Delete device data

Here, the code for Device.php (Model file)

<?php

namespace App\Models;

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

class Device extends Model
{
    use HasFactory;

    protected $fillable = [
        "name", 
        "status"
    ];
}

Controller file – DeviceController.php

<?php

namespace App\Http\Controllers;

use App\Models\Device;
use Illuminate\Http\Request;

class DeviceController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $all_devices = Device::all();

        return view("crud.index", [
            "devices" => $all_devices
        ]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view("crud.create");
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $device = new Device();

        $device->name = $request->name;
        $device->status = $request->status;

        $device->save();

        $request->session()->flash("success", "Device created successfully");

        return redirect("device");
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Device  $device
     * @return \Illuminate\Http\Response
     */
    public function show(Device $device)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Device  $device
     * @return \Illuminate\Http\Response
     */
    public function edit(Device $device)
    {
        return view("crud.edit", [
            "device" => $device
        ]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Device  $device
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $device = Device::find($id);

        $device->name = $request->name;

        $device->status = $request->status;

        $device->save();

        $request->session()->flash("success", "Data updated successfully");

        return redirect("device");
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Device  $device
     * @return \Illuminate\Http\Response
     */
    public function destroy(Device $device)
    {
        $device->delete();

        return redirect()->route("device.index")->with("success", "Device deleted successfuly");
    }
}

Create Read Update Delete

Create & Save Operation

public function store(Request $request) {
    //...
}

Update Operation

public function update(Request $request, $id) {
    //...
}

Delete Operation

public function destroy(Device $device) {
    //...
}

Here, we have taken a CRUD sample application.

Now,

We will create model events and attach with this CRUD application.

Read More: Laravel 10 Working with Eloquent Mutators and Accessors

Create Laravel Events – For Model Events

Open project into terminal and run these artisan commands.

$ php artisan make:event DeviceCreatingEvent

$ php artisan make:event DeviceCreatedEvent

Above commands will create DeviceCreatingEvent.php & DeviceCreatedEvent.php inside /app/Events folder.

Initially Events folder will not be available, but once we create events folder will be auto created.

Open DeviceCreatingEvent.php and write this complete code into it.

<?php

namespace App\Events;

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;
use App\Models\Device;

class DeviceCreatingEvent
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $device;
    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct(Device $device)
    {
        $this->device = $device;
    }

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

Open DeviceCreatedEvent.php and write this complete code into it.

<?php

namespace App\Events;

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;
use App\Models\Device;

class DeviceCreatedEvent
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $device;
    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct(Device $device)
    {
         $this->device = $device;
    }

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

Create Laravel Listeners – To Listen Events

Open project into terminal and run these artisan commands.

$ php artisan make:listener DeviceCreatingEventListener --event=DeviceCreatingEvent

$ php artisan make:listener DeviceCreatedEventListener --event=DeviceCreatedEvent

Above commands will create DeviceCreatingEventListener.php & DeviceCreatedEventListener.php inside /app/Listeners folder.

Initially Listeners folder will not be available, but once we create listeners folder will be auto created.

Open DeviceCreatingEventListener.php and write this complete code into it.

<?php

namespace App\Listeners;

use App\Events\DeviceCreatingEvent;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Facades\Log;

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

    /**
     * Handle the event.
     *
     * @param  DeviceCreatingEvent  $event
     * @return void
     */
    public function handle(DeviceCreatingEvent $event)
    {
        Log::info("Device creating process running...".$event->device);
    }
}

Open DeviceCreatedEventListener.php and write this complete code into it.

<?php

namespace App\Listeners;

use App\Events\DeviceCreatedEvent;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Support\Facades\Log;

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

    /**
     * Handle the event.
     *
     * @param  DeviceCreatedEvent  $event
     * @return void
     */
    public function handle(DeviceCreatedEvent $event)
    {
        Log::info("Device created successfully....".$event->device);
    }
}

Link Listeners to Laravel Events

Open EventServiceProvider.php from /app/Providers folder.

Search for $listen. Add your events classes into it.

<?php

namespace App\Providers;

use Illuminate\Auth\Events\Registered;
use Illuminate\Auth\Listeners\SendEmailVerificationNotification;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Event;

class EventServiceProvider extends ServiceProvider
{
    /**
     * The event listener mappings for the application.
     *
     * @var array
     */
    protected $listen = [
        Registered::class => [
            SendEmailVerificationNotification::class,
        ],
        \App\Events\DeviceCreatingEvent::class => [
            \App\Listeners\DeviceCreatingEventListener::class
        ],
        \App\Events\DeviceCreatedEvent::class => [
            \App\Listeners\DeviceCreatedEventListener::class
        ]
    ];

    /**
     * Register any events for your application.
     *
     * @return void
     */
    public function boot()
    {
        //
    }
}

Concept

//...

\App\Events\DeviceCreatingEvent::class => [
   \App\Listeners\DeviceCreatingEventListener::class
],
\App\Events\DeviceCreatedEvent::class => [
   \App\Listeners\DeviceCreatedEventListener::class
]

//...

Read More: How To Crop Image Before Upload in Laravel 10 Using Croppie.js

Add Model Events

Open Device.php from /app/Models folder and add these events.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use App\Events\DeviceCreatingEvent;
use App\Events\DeviceCreatedEvent;

class Device extends Model
{
    use HasFactory;

    protected $fillable = [
        "name", 
        "status"
    ];

    protected $dispatchesEvents = [
        "creating" => DeviceCreatingEvent::class,
        "created" => DeviceCreatedEvent::class,
        //..
    ]; 
}

How Process is Running?

When we perform Create/Save operation via Model i.e Create device and save to database table.

Model events creating (before create) & created (after create) will be triggered.

creating event calls DeviceCreatingEvent::class whereas created event calls DeviceCreatedEvent::class.

DeviceCreatingEvent & DeviceCreatedEvent are laravel events that we created.

Next,

DeviceCreatingEventListener::class listens DeviceCreatingEvent::class where as DeviceCreatedEventListener::class listens DeviceCreatedEvent::class.

handle() of each listeners will be executed.

Application Execution

When we run CRUD application, logs will be logged into /storage/logs/laravel.log file.

[2022-03-08 01:30:51] local.INFO: Device creating process running… {"name":"Device 100","status":"0"}  
[2022-03-08 01:30:52] local.INFO: Device created successfully….{"name":"Device 100","status":"0","updated_at":"2022-03-08T01:30:51.000000Z","created_at":"2022-03-08T01:30:51.000000Z","id":4}  

We hope this article helped you to Learn Laravel 10 How To Work with Model Events And Listeners in a very detailed way.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Sanjay KumarHello friends, I am Sanjay Kumar a Web Developer by profession. Additionally I'm also a Blogger, Youtuber by Passion. I founded Online Web Tutor and Skillshike platforms. By using these platforms I am sharing the valuable knowledge of Programming, Tips and Tricks, Programming Standards and more what I have with you all. Read more