Gazzer
Gazzer

Reputation: 4656

How to implement events in Laravel 5.5

The Laravel Eloquent Event docs give this example:

namespace App;

use App\Events\UserSaved;
use App\Events\UserDeleted;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The event map for the model.
     *
     * @var array
     */
    protected $dispatchesEvents = [
        'saved' => UserSaved::class,
        'deleted' => UserDeleted::class,
    ];
}

I simply want to know what would go in a UserSaved::class to, let's say, add a hash id on the initial save. The docs are frustratingly opaque at this point!

Upvotes: 0

Views: 1131

Answers (2)

Lionel Chan
Lionel Chan

Reputation: 8069

In any of your model event classes, just do this:

For example: App\Events\UserSaved.php

<?php

namespace App\Events;

use Illuminate\Queue\SerializesModels;

class UserSaved
{

    use SerializesModels;

    /**
     * @var \App\User
     */
    public $user;

    public function __construct($user)
    {
        // All dispatched model events will receive an instance
        // of the model itself. Usually, we'll just assign
        // it as a property of this event class
        $this->user = $user;
    }
}

Dispatched event are supplied with the model instance, as shown in the source code:

Documentation: Defining Events

So at the later time when your listeners caught this event, they will have an instance of this UserSaved object, and you can just access user from $userSaved->user.

Upvotes: 1

lagbox
lagbox

Reputation: 50531

It would be an event class, it takes the current model the event is being fired for in its constructor.

"An event class is simply a data container which holds the information related to the event. " Laravel 5.5 Docs - Events - Defining Events

You will need to setup a listener to listen for your custom event object you are now firing instead of the eloquent string event it would normally fire. In the listener(s) you can react to this event.

Upvotes: 0

Related Questions