Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

GodziLaravel's avatar

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

0 likes
3 replies
Nakov's avatar
Nakov
Best Answer
Level 73

@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
}
bugsysha's avatar
    /**
     * 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.

1 like
bugsysha's avatar

If you are going with getDirty then array_intersect is far cleaner than what was suggested.

Please or to participate in this conversation.