I have an Eloquent model. Whenever it is retrieved from the database I would like to check whether a condition is fulfilled and set a model attribute if this is the case.
EDIT: I initially thought that the restoring
event would be the right place to put the relevant logic, but as Tyler Crompton points out below, restoring
is fired before a soft-deleted record is restored.
You could do this on the way in, or the way out. It seems like you wanted it stored in the database, so you could use mutators.
When ever
B
is set, it will check againstA
, and store1
inB
.Side note: Note the
B
between set and attributeYou have two valid options:
\Illuminate\Datebase\Eloquent\Model
to add such an event.\Illuminate\Datebase\Eloquent\Model
to add this (and possibly send an (unsolicited) pull request to Laravel on GitHub). According to Issue 1685, it looks as though they do not want it.If I were you, I'd go with the first option and this is how I'd do it:
Just make sure the models in question subclass from
LoadingModule
. I have confirmed this to work as I found a great use case for it. Older versions of PHP returned MySQL values as strings. Normally, PHP will silently cast these to their respective numeric types in numeric operations. However, converting to JSON is not considered a numeric operation. The JSON values are represented as strings. This can cause problems for clients of my API. So I added aloaded
event to my models to convert values to the correct type.