Laravel 4 how to listen to a model event? - laravel

I want to have an event listener binding with a model event updating.
For instance, after a post is updated, there's an alert notifying the updated post title, how to write an event listener to have the notifying (with the post title value passing to the listener?

This post:
http://driesvints.com/blog/using-laravel-4-model-events/
Shows you how to set up event listeners using the "boot()" static function inside the model:
class Post extends eloquent {
public static function boot()
{
parent::boot();
static::creating(function($post)
{
$post->created_by = Auth::user()->id;
$post->updated_by = Auth::user()->id;
});
static::updating(function($post)
{
$post->updated_by = Auth::user()->id;
});
}
}
The list of events that #phill-sparks shared in his answer can be applied to individual modules.

The documentation briefly mentions Model Events. They've all got a helper function on the model so you don't need to know how they're constructed.
Eloquent models fire several events, allowing you to hook into various points in the model's lifecycle using the following methods: creating, created, updating, updated, saving, saved, deleting, deleted. If false is returned from the creating, updating, saving or deleting events, the action will be cancelled.
Project::creating(function($project) { }); // *
Project::created(function($project) { });
Project::updating(function($project) { }); // *
Project::updated(function($project) { });
Project::saving(function($project) { }); // *
Project::saved(function($project) { });
Project::deleting(function($project) { }); // *
Project::deleted(function($project) { });
If you return false from the functions marked * then they will cancel the operation.
For more detail, you can look through Illuminate/Database/Eloquent/Model and you will find all the events in there, look for uses of static::registerModelEvent and $this->fireModelEvent.
Events on Eloquent models are structured as eloquent.{$event}: {$class} and pass the model instance as a parameter.

I got stuck on this because I assumed subscribing to default model events like Event:listen('user.created',function($user) would have worked (as I said in a comment). So far I've seen these options work in the example of the default model user created event:
//This will work in general, but not in the start.php file
User::created(function($user)....
//this will work in the start.php file
Event::listen('eloquent.created: User', function($user)....

Event::listen('eloquent.created: ModelName', function(ModelName $model) {
//...
})

Related

Laravel or Nova have the same model attributes on updating Event and update Event

Simple callback to trace updating event (the before update event):
protected static function booted()
{
static::updating(function (Question $question) {
// $question->name will be the same as in the 'update' event which might look strange
});
static::update(function (Question $question) {
});
}
Why attributes of updating and update events are the same?
To get the previous value you should use getOriginal method:
if ($question->name != $question->getOriginal('name')) {
// this value was changed so you may add more logic
}
Same applicable to creating and created events.

Laravel deleting cache working in controller but not in model closure

I'd like to delete a specific model from the cache using its id. This works as expected in the controller, but not using the model closure.
What I have in App\Models\Post:
use Illuminate\Support\Facades\Cache;
protected static function booted()
{
static::updated(function ($post) {
Cache::forget('post:'.$post->id);
});
}
If I do Cache::forget('post:'.$post->id); in the controller it works.
Something I'm missing?
Make sure that you are actually changing a value on your model, because the updated event only fires when the model was dirty, as you can see here.
The saved event however will fire whenever you call the save() method, as you can see here:
protected static function booted()
{
static::saved(function ($post) {
Cache::forget('post:'.$post->id);
});
}
From the docs:
The retrieved event will fire when an existing model is retrieved from
the database. When a new model is saved for the first time, the
creating and 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.

Listen to Event : User::creating

I'm doing a new plugin for OctoberCms. I would like to limit the front end registration for some specific domains.
I tried to this :
class Plugin extends PluginBase
{
[......]
public function boot()
{
// Listen for user creation
Event::listen('eloquent.creating: October\Rain\Auth\Models\User', function($model) {
{
$this->checkDomains($user);
[.....]
}
}
}
But my listener is not working. Do you know what is the Event, I should listen to catch before a new account is created ?
Thanks
You can bind to all of the model internal events like this:
User::extend(function($model) {
$model->bindEvent('model.beforeSave', function() use ($model) {
// do something
});
});
You can use before and after for create, update, save, fetch and delete
Alternatively, you can use,
public function boot()
{
User::creating(function($model) {
var_dump($model->name);
});
}
available events to listen:
creating, created, updating, updated, deleting, deleted, saving, saved, restoring, restored
You can also use the following:
\Event::listen('eloquent.creating: RainLab\User\Models\User', function($user){
$this->checkDomains($user);
});
Are you referring to a Front-End User's registration ? - I assumed you're using the RainLab User Plugin which has an event rainlab.user.beforeRegister fired in the Account component or you can add a custom one in the model's beforeCreate() event
then simply create a init.php file in the root directory of your plugin and list your listeners there :
Event::listen('rainlab.user.beforeRegister', 'Path\To\ListenersClass');

Prevent Certain CRUD Operations on Laravel Eloquent Models

Is there an easy way to prevent certain CRUD operations from being performed on an Eloquent model?
How I'm doing it now (from memory, I think I'm missing an argument to be compatible with Eloquent's save(), but that's not important):
<?php
class Foo extends Eloquent {
public function save()
{
// Prevent Foo from being updated.
if (!empty($this->id)) {
throw new \Exception('Update functionality is not allowed.');
}
parent::save();
}
}
In this case, these models should not be allowed to be updated under any circumstance, and I want my app to explode should something try to update them. Is there a cleaner way to do this without overriding Eloquent's save() method?
In addition to #AlanStorm's answer, here's a comprehensive info:
You can setup global listener for all the models:
Event::listen('eloquent.saving: *', function ($model) {
return false;
});
Or for given model:
Event::listen('eloquent.saving: User', function ($user) {
return false;
});
// or
User::saving(function ($user) {
return false;
});
// If it's not global, but for single model, then I would place it in boot():
// SomeModel
public static function boot()
{
parent::boot();
static::saving(function ($someModel) {
return false;
});
}
For read-only model you need just one saving event listener returning false, then all: Model::create, $model->save(), $model->update() will be rejected.
Here's the list of all Eloquent events: booting, booted, creating, created, saving, saved, updating, updated, deleting, deleted and also restoring and restored provided by SoftDeletingTrait.
Eloquent's event system allows you to cancel a write operation by
Listening for the creating, updating, saving, or deleting events
Returning false from your event callback.
For example, to prevent people from creating new model objects, something like this
Foo::creating(function($foo)
{
return false; //no one gets to create something
});
in your app/start/global.php file would do the job.

Are cake events handled asynchronously?

At the moment I don't have any queuing functionality in my Cakephp aplication. I will need that in the near future. An upload will result in a batchjob that uses external API with usage limitations, so it would be best if it was handeled in a seperate threat with a queue.
I don't have any experience with this, so I'm going to try a different, but easier, example.
User actions result in e-mails being send. At the moment, the loading of the page is delayed by the (rather long) time it takes the server to send the e-mail. I'd like to use the Event system to fix this. (I am aware I can also do this using this the afterRender function, or dispatch it to a shellTask, but that way I don't learn anything)
From the example page:http://book.cakephp.org/2.0/en/core-libraries/events.html
I've found this example:
// Cart/Model/Order.php
App::uses('CakeEvent', 'Event');
class Order extends AppModel {
public function place($order) {
if ($this->save($order)) {
$this->Cart->remove($order);
$this->getEventManager()->dispatch(new CakeEvent('Model.Order.afterPlace', $this, array(
'order' => $order
)));
return true;
}
return false;
}
}
Let's say the function was called by a controller action:
public function place_order() {
$result = $this->Order->place($this->request->data);
$this->set('result', $result);
}
Now my question... Will the corresponding view be rendered after all the dispatched events completes? or will the Model function just trigger the event and then forget about it?
The last option seems more logical to me (which also resembles the mentioned jQuery functionality in the article)
The problem is that If this were true, I don't understand the later example:
In the example about using results:
// Using the event result
public function place($order) {
$event = new CakeEvent('Model.Order.beforePlace', $this, array('order' => $order));
$this->getEventManager()->dispatch($event);
if (!empty($event->result['order'])) {
$order = $event->result['order'];
}
if ($this->Order->save($order)) {
// ...
}
// ...
}
if the event was just triggered (and then forgot about) there is no way you can asume it has modified the passed event object on the next line of code!
I would like to use cake as much as possible, but I'm not sure if I can get my desired background behavior without shellTasks and external queue. Any tips about these Cake Events?
Cake Events are triggered synchronously. When an event is triggered, all available listeners are called, before proceeding with other instructions.
You can imagine it on your second example as:
public function place($order) {
$event = new CakeEvent('Model.Order.beforePlace', $this, array('order' => $order));
$this->getEventManager()->dispatch($event); // -> all listeners are called at this point
// ... here you can assume your $event was modified
if (!empty($event->result['order'])) {
$order = $event->result['order'];
}
if ($this->Order->save($order)) {
// ...
}
// ...
}

Resources