Back

How could I create custom Model Events?


codeATbusiness posted 4 years ago

Is possible to create custom model events as creating, created, updating, update, ...?

Thanks in advanced.

mikenolimits replied 4 years ago

Yes it is possible.

More information can be viewed here: https://laracasts.com/lessons/model-events

mcraz replied 4 years ago

Eloquent models already fire a bunch of events.

Additionally you can create custom events.

codeATbusiness replied 4 years ago

Yes, but can we create custom model-events? or only custom events?

codeATbusiness replied 4 years ago

Correct me if I don't be mistaken.

I found in the Model.php the following sentences:

    /**
 * Get the observable event names.
 *
 * @return array
 */
public function getObservableEvents()
{
	return array_merge(
		array(
			'creating', 'created', 'updating', 'updated',
			'deleting', 'deleted', 'saving', 'saved',
			'restoring', 'restored',
		),
		$this->observables
	);
}

And later the custom creating, created, and several other methods:

     /**
 * Register a creating model event with the dispatcher.
 *
 * @param  \Closure|string  $callback
 * @return void
 */
public static function creating($callback)
{
	static::registerModelEvent('creating', $callback);
}

Is correct to add to the array of events observables the new event and later define the custom event method with its callback?

Is anybody know another method to define it, please tell me.

Thanks in advanced

mcraz replied 4 years ago

Can you give an example of an model-event you would like to fire.

codeATbusiness replied 4 years ago

I have two custom Models:

-User
-Courses

By example I like to fire custom events as follow:

User::course_adding

User::course_added

Course::user_adding

Course::user_added

... another custom events

Thanks for your replies.

mcraz replied 4 years ago

Still unclear. It would be helpful if you can just explain for what action do you want to fire event.

Like : I want to fire an event named user.signup whenever a new user signs up to my website.

codeATbusiness replied 4 years ago

I want to fire and event called Course.userAdded when a course have a user added to its user list.

Imagine that you have a Users table and a Course tables, and you have a courses_users table to list the courses and the users registered within.

When you add an users to the Courses I like to fire this custom event course.user_added.

I know that I could use the course::updating o course::updated but I like to create custom events ad hoc.

mcraz replied 4 years ago Solution

That is not a model event since it is not specific to a single element.

So, you should be defining that when you are creating the relationship.

For example :

// Suppose to add a user to a course, you do :

$course = Course::find(1);

$user = Auth::user();

$course->attenders()->attach($user->id);

// So you should fire an event here.

$event = Event::fire('user_added_to_course', $user, $course);

codeATbusiness replied 4 years ago

Many thanks.

But only a question, When you are firing a creating event of a Sale Model by example, and this Sale creation is based on a Item Model and a User Model, is not aproximate to my question?

savanihd replied 6 months ago

You can simply create event with model,Here is simple example : https://hdtuto.com/article/how-to-create-events-for-created-updated-deleted-model-task-in-laravel-5

Sophia Wilson replied 5 months ago

You want to see it in observers to make it more reusable and single-responsible, although the starting point will be equally:

public function boot()

{

self::updated(function ($model) {

    if (array_key_exists('category_id', $model->getDirty())) {

        // Log things here

    }

});

}

Laravel will create a 'dirty' array that includes modified fields. You can find out that a specific area has changed using this.

You also have:

$model->getOriginal('field_name') // for this field value (originally)

$model->getOriginal() // for all original field values

John replied 4 months ago

new event 'viewed':

use Illuminate\Database\Eloquent\Model;

class History extends Model 
{
    public function getObservableEvents()
    {
        return array_merge(
            parent::getObservableEvents(),
            ['viewed']
        );
    }

    public static function viewed($callback)
    {
        static::registerModelEvent('viewed', $callback);
    }

    protected static function boot(){
        parent::boot();

        static::viewed(function($model)
        {
            dd($model);
        });
    }
}

fire event

event("eloquent.viewed: " . \get_class($model), $model);

Sign in to participate in this thread!



We'd like to thank these amazing companies for supporting us