Author

Using Events on Laravel Eloquent

Image

by Samarth Sinha on 2017-04-07 16:50:27

Eloquent models fire several events, allowing you to hook into the following points in a model's lifecycle: creating, created, updating, updated, saving, saved, deleting, deleted, restoring, restored. Events allow you to easily execute code each time a specific model class is saved or updated in the database.

Whenever a new model is saved for the first time, the creating, created events will fire. If a model already existed in the database and the save method is called, the updating, updated events will fire. However, in both cases, the saving, saved events will fire.

To get started, define an $events property on your Eloquent model that maps various points of the Eloquent model's lifecycle to your own event classes:

protected $events = [
        'saved' => UserSaving::class,
    ];

Now go to EventServiceProvider class in your app/provider folder, and add the events and their listener to the $listen variable.

protected $listen = [
    'App\Events\UserSavingEvent' => [
        'App\Listeners\UserSavingEventListener',
    ],
];

Then run the commands php artisan event:generate to generate your events. The Events and Listener folder will be created to your app folder. Now go to your UserSavingEvent class and write the following codes.

<?php

namespace App\Events;

use App\User;

class UserSavingEvent
{
    public $user;

    public function __construct(Order $user)
    {
        $this->user = $user;
    }
}

Now got to your UserSavedEventListener class and write following codes.

<?php

namespace App\Listeners;

use App\Events\UserSavingEvent;

class UserSavingEventListener
{
    public function handle(UserSavingEvent $event)
    {
        // Access the order using $event->user...
        // Do Something... like validation or any action you want to perform before storing the record on the table.
    }
}

You should always do validations on model. Similarly you can create saved, updating, updated, etc. events.

 


Viewer Comments (1)

About the Author

  • avatar
    Samarth Sinha

    My name Samarth Sinha. I work on developing Web Applications using PHP and MySQL and in different frameworks of PHP like Laravel, CakePHP, CodeIgnitor and Smarty. In databases I have worked in MySQL and Postgres. I started this blog to share my knowledge to those who wants to start developing Web Applications using PHP.