LMSouq
php-dev Open

Add a custom attribute to a Laravel / Eloquent model on load?

CO
coatesap
1 month ago
3 views
Problem Description
I'd like to be able to add a custom attribute/property to an Laravel/Eloquent model when it is loaded. 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 [1]: http://redbeanphp.com/manual/models_and_fuse

AI-Generated Solution

Powered by LMSouq AI · GPT-4.1-mini

✓ Solution Ready
Analyzing problem and generating solution…
Was this solution helpful?
Back to Knowledge Base