I am building a notification system at the moment, and the notifications get delivered via model events. Some of the notifications are dependent on things happening with the models relationships.
Example: I have a project model that has a one:many relationship with users,
public function projectmanager() {
return $this->belongsToMany('User', 'project_managers');
}
I am wanting to monitor for changes on this relationship in my project model events. At the moment, I am doing this by doing this following,
$dirtyAttributes = $project->getDirty();
foreach($dirtyAttributes as $attribute => $value) {
//Do something
}
This is run in the ::updating
event of the model but only looks at the models attributes and not any of it's relational data, is it possible get old relational data and new relational data to compare and process?
You should be using an observer class for this.
This has already been covered fairly simply and well by this SO answer, although that answer uses a slightly older method where the class itself needs to call upon its observer. The documentation for the current version (5.3 as of this answer) recommends registering the observer in your application service provider, which in your example would look similar to:
<?php
namespace App\Providers;
use App\Project;
use App\Observers\ProjectObserver;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
Project::observe(ProjectObserver::class);
}
}
For evaluating the differences between the new model values and the old values still in the relational DB, Laravel provides methods for both: getDirty()
and getOriginal()
.
So your observer would look something like:
<?php
namespace App\Observers;
use App\Project;
class ProjectObserver
{
/**
* Listen to the Project updating event.
*
* @param Project $project
* @return void
*/
public function updating(Project $project)
{
$dirtyAttributes = $project->getDirty();
$originalAttributes = $project->getOriginal();
// loop over one and compare/process against the other
foreach ($dirtyAttributes as $attribute => $value) {
// do something with the equivalent entry in $originalAttributes
}
}
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments