Laravel 4 Restored model event not firing - laravel-4

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?

Related

Laravel: restore() and update() in one query?

New to laravel, In my case, I have 3 actions (move to active, inactive, and deleted)
when moved to active/inactive, the status column in database is changed,
when deleted, it gets soft deleted (without changing the status column),
Now, when the deleted rows are being moved to active/inactive, I should use restore() and at the same it, update the status column as specified.
But I can't find any docs regarding this use case.
You may write some helper method for Model to do though
I know this is not exactly the answer of your question but using these you can active/inactive your model without knowing about how it works and also it prevents redundant codes all over the project.
use Illuminate\Support\Facades\DB;
protected function toggleStatus($status) {
DB::transaction(function () use($status) {
$this->restore();
$this->update(['status' => $status]);
});
}
public function active() {
$this->toggleStatus('active');
}
public function inactive() {
$this->toggleStatus('inactive');
}

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.

How to hook into the delete event for a resource in laravel nova?

I have one query, I want to delete the image from the server when particular resource get deleted from Nova.
can anyone suggest me is there any way to override delete method for the resource.
EDIT: How to hook into the delete event for a resource in laravel nova?
Note: I know we can do using observer. but I am looking for another
way.
In order to hook into laravel nova's delete resource event, you don't have a builtin way. But the parent model's have a delete method, you can override it and do extra work there
//app/ParentModel.php
public function delete() {
/* add your extra logic for deleted model */
parent::delete();
}
you can use boot in your model like this:
public static function boot()
{
parent::boot();
self::deleted(function ($model) {
parent::remove($model, self::$index);
});
}
I used Observers and deleted function Nova Resource Events and works fine

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.

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