Henry Bui
Henry Bui

Reputation: 703

How to get original accessor data when update Model Laravel?

I want to write before and after data to logs table when updating an instance.

I'm getting beforeUpdate(original) data by getOriginal() method, but I don't know how to get data related to original data.

Ex:

Table campaigns has field campaign_status_id.

I have an Accessor is getCampaignStatusNameAttribute(), this method will get relationship between campaigns table and campaign_status table and return campaign_status_name.

If I update campaign status and call getCampaignStatusNameAttribute(), I just receive updated data only. Of course, I can write a custom function and pass the campaign_status_id as a param to get data but I want to know any better solutions.

Any solution to get the original Accessor?

Upvotes: 0

Views: 1245

Answers (1)

Koushik Das
Koushik Das

Reputation: 10803

In order to get the original data, you use

$model->getAttributes()['column_name']

or this

Arr::get($model->getAttributes(), 'column_name', 'default_value_here') // default value can be null

Make sure to import this Arr helper facade at the top if you're using the Arr way. The advantage of the Arr way is that even if the value doesn't exist, it would not return any error and you can always return some default value if the value didn't exist.

getOriginal will return the modified if it was called recently. That's not really the most reliable way.

Upvotes: 1

Related Questions