Neelkanth Kaushik
Neelkanth Kaushik

Reputation: 245

How to get the total number of updated fields in laravel 5.1?

I need to save the number of fields updated after an update operation is performed on a model and its related models.

Suppose I have a user profile edit form. On that form I allow the user to update its firtname, lastname, password.

The User model has email and password fields and few other fields as well.

The UserProfile model has firstname, last name and other fields as well.

The User model is associated with UserProfiles model with hasOne association.

There are some ManyToMany and hasMany associations as well.

If the user updates firstname and password I need to show user the "number of fields changed : 2".

Is there any Laravel 5 way or package to do so.

Thanks.

Upvotes: 3

Views: 443

Answers (1)

thefallen
thefallen

Reputation: 9749

You can use the getDirty() method of the Eloquent model like this:

$data = ['email' => '[email protected]', 'name' => 'John Doe'];
$user = User::find(1);

$user->fill( $data );

if ( !$user->isDirty() ) {
    //NO DATA CHANGED
}

$numberOfChanges = count( $user->getDirty() );

The getDirty() will return an array of the changed properties of the model, so when you count the size of the array you'll have exactly how many fields there were changed.

Please note that I've used the User model only for example and $data would probably come from the request.

Upvotes: 2

Related Questions