What do you do in the function? Is a local scope, or just a function that have a lot of logic? Let's give me the custom function code
How can I include a model function with this query?
I have a location model which has a custom function. Let's call it myCustomFunction for example. In my controller I am defining my query like this
$locations = Location::with('lobs', 'dashboards', 'alerts')
->withCount('lobs')
->get();
However, I need to include myCustomFunction with the result set. I am not sure how to do this. Can anyone help me out here?
Your query results in a Collection of Location instances; if you have defined a custom function on the Location model class, then each instance has that method:
locations = Location::with('lobs', 'dashboards', 'alerts')
->withCount('lobs')
->get();
// e.g. Iterate over the Collection an call the method on each instance
foreach ($location in $locations) {
$location->myCustomFunction();
}
If you wish to have a computed attribute then you can create an accessor method, it follows the pattern getAbcdAttribute() resulting in a $location->abcd property being available on the model instances. You can ensure it is included in an array representation of the model instance by including it in the $appends properties on the model.
https://laravel.com/docs/6.x/eloquent-mutators#defining-an-accessor
Please or to participate in this conversation.