简体   繁体   中英

How to update on data restauration in a Laravel Eloquent model?

I would like to be able to run some code when an Eloquent model is loaded from my database. fill() does not seem to be the right method as it is not code when I load get my object from a query.

Context aka "why would someone want to do that"

I wish my object to have some complex attributes which are currently represented as public properties, persisted as JSON on save and I need to restore them back on loading from database.

Laravel: 5.6

The event you're looking for is retrieved , though mentioned in the laravel documentation, not very obvious compared to the other events, you can either do it like this or delegate it to an observer class:

Model::retrieved(function(Model $model) {
    $model->foo = json_decode($this->json)['foo']; // '{"foo":"bar"}'
})

(and yes, this event runs after it has been retrieved from the database, but before your other code)

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