Is there any way to get the original value of an attribute of a Model then modify it?

Asked

Viewed 86 times

1

I am using the Laravel 5 and would like to know if, after modifying an attribute of a model, it is possible to recover it.

For example:

 $usuario = Usuario::where(['nome' => 'Wallace'])->first();

 $usuario->nome = 'Guilherme';

In the above example, I modified the attribute nome model. I wonder if you can recover the attribute nome. Laravel "saves" the original value somewhere before saving the changes?

Of course I could do this by doing another consultation, but I don’t think this is the best way. So I won’t accept answers like.

I wonder if there is any way to recover the initial value of the "name" attribute of the model above, without making another query.

  • 1

    why don’t you take the next line of $usuario = Usuario::wher... this: $nomeOrig = $usuario->nome. And then keep the original name returned saved. This is if I understood the question correctly

  • It’s @Miguel, too, but if it was multiple camps, I’d have to do it one by one, right? In fact I know the answer, just really wanted to instigate to have more content from [tag:Laravel] on the site and see the creativity of the staff :D

  • I await your reply then... I am also curious. That is after making $user->save(); recover the data that was there before?

  • 1

    @Miguel no, I said "before". " After" I already know that there is no way, because the data are already from the table :D

  • Yes, of course, but it could be that I was in session implicitly without us knowing

  • Curious ok anyway. I get what you mean. But I don’t know

  • 1

    @Miguel actually has the getOriginal :D. I’ve said too much

  • I just saw yes. But that doesn’t hide the pass/token. I tested it here

Show 3 more comments

1 answer

3


Laravel saves the original model attributes inside the property original.

$user = User::first();

$user->name = 'Rafael';

dd(
    $user->getAttributes(), // contém o atributo nome novo.
    $user->getOriginal() // contém o atributo nome antigo.
);

If you want to access an attribute specific to the original values, just pass its name by parameter Model::getOriginal.

Example:

  $user->getOriginal('name');

You can check directly into the api, in this link.

  • If I may, I’ve added a few details :p

Browser other questions tagged

You are not signed in. Login or sign up in order to post.