How can I update just the changes in model?

Posted 8 months ago by alihoushyaripour

Hi,

I want to update a model(only properties that have changed) like user, in repository I write this:

public function update($id, $username, $firstName, $lastName)
{
    // user
    $user = new User()::find($id);

    // username
    if ($user->username !== $username) {
        $user->username = $username;
    }

    // first_name
    if ($user->first_name !== $firstName]) {
        $user->first_name = $firstName];
    }

    // last_name
    if ($user->last_name !== $lastName) {
        $user->last_name = $lastName;
    }

    // save
    $user->save();

    // success
    return true;
}

Is there any better way? this take a lot of line.

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.