Laravel deleting cache working in controller but not in model closure - laravel

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.

Related

Updating a model property by POST API, can run an event?

The clear description is, an API with the post method updates a value of a model property. how I can set up a listener in Laravel that after every change by API, run an event for example send email or sms?
If you were wanting to create an event when any update happened you could easily just do this via the boot.
class SomeModel extends Model
{
public static function boot()
{
static::updated(function ($model) {
// send your email/sms
});
parent::boot();
}
}
However this would trigger when ever the model is updated, Since you only want this when you are updating via the API you would want to create a custom event and trigger it via dispatch in your api route/controller.
https://laravel.com/docs/8.x/events#dispatching-events

Eloquent model getRawOriginal() returns new values in `updating` observer

I need to compare original model values with changes that are done when update occurs, but I am not able to do that.
My model update code looks like this:
public function update(array $user, int $userId): ?bool
{
return User::find($userId)->update($user);
}
I thought that the best way to capture changes is to use observer and observe updating event, because I assume it's called right before changes are stored in the database. Here is updating method code:
public function updating(User $user)
{
Log::info('Original user', ['original' => $user->getRawOriginal('status')]);
}
I've tried logging a bit and it seems that updating method gets called after the update happens and then when I try to retrieve original model values there it returns new ones, instead of the original ones.
If I use getChanges() method in updating it returns exactly what has changed, so it seems that changes are tracked somehow, but not the original values?
Can someone give me any pointers how to solve this and explain to me why my approach doesn't work?
Update: Code, where I call update, is wrapped with DB transaction methods. After removing them it seems that updating method gets called at the right time and getRawOriginal then returns expected results.
In this case, what are my options? Is there a way to do what I want without removing transactions?
You can add boot method in your model .Both updating and updated trigger while updating .
protected static function boot()
{
parent::boot();
static::updating(function ($model){
echo "updating";
dump($model->getDirty());
dump($model->getRawOriginal('username'));
});
static::updated(function ($model){
echo "updated";
dump($model->getDirty());
dump($model->getRawOriginal('mobile_number'));
});
}

Laravel Cancel Creation of Object

I have a Laravel app which has an object, Position, which is created via a form.
class Position extends Model
{
protected $dispatchesEvents = [
'creating' => PositionCreating::class,
];
And this calls an event of the PositionCreating class, which I've tested, and is correctly firing. The underlying code also works to give me success or fail criteria.
class PositionCreating
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public function __construct(Position $position)
{
if (some_good_stuff())
{
//keep creating the object
} else {
//stop creating the object
}
}
If it works, that's fine, I just let the __construct() function finish executing and everything, including the pre-execution code I want, works perfectly.
But I don't know how to actually stop the creation of the object. I can, of course use the dd() function or something (which works and stops creation of the object as expected), but I want to present a readable error to the user in a friendly manner. What function or commands should I be using to cancel the creation of the object to return back to my position.create method?
A bit late answer but this is a way to do it. Models fire several events. The one you're looking for is probably the "created" event. Each model event receive an instance of the model so you could just attach an event on your model, just like this:
protected $dispatchesEvents = [
'created' => PositionCreated::class,
];
Inside your "PositionCreated" event, add a public property to get the model instance,like this:
public $position;
public function __construct(Position $position)
{
$this->position=$position;
}
Finally just add the logic on your "handle" method inside your event listener.
public function handle($event)
{
if($something)
{
$event->position->delete();
}
}
This should do the work.You can check for the other events and see wich one suits you the most.

Laravel 4 Restored model event not firing

I am trying to get the following code to work with two models using soft deletes. The deleted event fires perfectly and cascade deletes the related models. However when I try to restore the model it fails to called the restored event and the related models are left as deleted.
public static function boot()
{
// make the parent (Eloquent) boot method run
parent::boot();
static::deleted(function ($artwork) {
$artwork->variants()->delete();
});
static::restoring(function ($artwork) {
$artwork->variants()->onlyTrashed()->restore();
});
}
Any ideas?

Laravel 4 how to listen to a model event?

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) {
//...
})

Resources