rsarvarov's avatar

Get "dirty" attributes of model (even if no changes)

I know about getDirty() method, that gives me properties that been changed (before save()). But what if I want to know properties that haven't changed at all (but It was setted)?

For example:

$user = User::where('name', 'Alex')->first(); // ID: 123, NAME: 'Alex', CITY: 'New York' etc...
$user->name = $user->name; 

So I want detect that there was try to change 'name' column. Is there any easy way to do that?

0 likes
4 replies
tykus's avatar

You know this is not a change, right?

$user->name = $user->name;
1 like
rodrigo.pedra's avatar
Level 56

You could override your model's setAttribute method and keep track there of any change attempts.

Something like this:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class MyModel extends Model
{
    protected $touched = [];
    
    public function setAttribute($key, $value)
    {
        // set as an array key to avoid duplicates
        $this->touched[$key] = true;
        
        return parent::setAttribute($key, $value);
    }

    public function getTouched()
    {
        return \array_keys($this->touched);
    }
}
rsarvarov's avatar

I probably found the solution (in model code):

    protected $touchedProperties = [];

    /**
     * @param $key
     * @param $value
     */
    public function setAttribute($key, $value)
    {
        $this->touchedProperties[$key] = $value;

        parent::setAttribute($key, $value);
    }
1 like
rodrigo.pedra's avatar

We posted it almost at the same time! Have a nice day =)

1 like

Please or to participate in this conversation.