简体   繁体   中英

MySQl/Laravel: check the changed column before updating the record

I have a table abc which has several fields.

I need to fetch the column or columns (except: id , created_at & updated_at ) which have been updated and store the existing value along with the column name in a logs table corresponding to that selected record before updating it in that table.

For example:
Table: abc

id: 1
name: 'Old name'
mobile: 9876543210
address: 'Abc-123'
...
created_at: 'Sometime'
updated_at: 'Sometime'

update:
    name: 'new name'
    mobile: 1234567890

Table: logs should have

column | value
name   | Old name

column | value
mobile | 9876543210

However, I can save the entire record in the table, which will be lot easier, but that will just be the waste of space/memory. Also, it will be difficult to determine which value was exactly changed at that point of time without any algorithm.

isDirty() method is use to check if the model or any of the given attribute(s) have been modified.

it will return true if name chagned: $model->isDirty('name')

you can also get Old value using getOriginal() method

Ex  : $old_name = $model->getOriginal('name');

Reference: https://laravel.com/api/master/Illuminate/Database/Eloquent/Model.html#method_isDirty

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM