I’d like to be able to add a custom attribute/property to an Laravel/Eloquent model when it is loaded, similar to how that might be achieved with RedBean’s $model->open()
method.
For instance, at the moment, in my controller I have:
public function index()
{
$sessions = EventSession::all();
foreach ($sessions as $i => $session) {
$sessions[$i]->available = $session->getAvailability();
}
return $sessions;
}
It would be nice to be able to omit the loop and have the ‘available’ attribute already set and populated.
I’ve tried using some of the model events described in the documentation to attach this property when the object loads, but without success so far.
Notes:
- ‘available’ is not a field in the underlying table.
$sessions
is being returned as a JSON object as part of an API, and therefore calling something like$session->available()
in a template isn’t an option