IsDirty : how to check only some fields ? Hello
How to verify only some fields using isDirty ?
$competence->obtained_date = $request->get('obtained_date');
$competence->target_date = $request->get('target_date');
$competence->comment = $request->get('comment');
$competence->objective_level = $request->get('objective_level');
$competence->current_level = $request->get('current_level');
$competence->save();
if($competence->isDirty(["comment","objective_level","current_level"])){
//doSomething()
}
I would like to call doSomething() only if "comment" or "objective_level" or "current_level" are changed !
the code above is not working .
Thanks
@mostafalaravel you can use the getDirty() method which returns an array, but then the check would be something like this:
$dirtyItems = $competence->getDirty();
if(in_array('comment', $dirtyItems) || in_array('objective_level', $dirtyItems) || in_array('current_level', $dirtyItems)) {
// do something
}
/**
* Determine if the model or any of the given attribute(s) have been modified.
*
* @param array|string|null $attributes
* @return bool
*/
public function isDirty($attributes = null)
{
return $this->hasChanges(
$this->getDirty(), is_array($attributes) ? $attributes : func_get_args()
);
}
That looks like it should work out of the box.
If you are going with getDirty then array_intersect is far cleaner than what was suggested.
Please sign in or create an account to participate in this conversation.