Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

premiSoft's avatar

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?

0 likes
8 replies
zhanang19's avatar

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

premiSoft's avatar

It doesn't actually do much. Just returns two fields from the locations table that are then concatenated together.

tykus's avatar
tykus
Best Answer
Level 104

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

premiSoft's avatar

public function getLocationSiteAttribute() { return $this->name . ' (' . $this->site_code . ')'; }

premiSoft's avatar

Ok.... I didn't realize that because when I used dd to see the result set, I didn't see it included..

tykus's avatar

Yeah, you won't see it in a dump of the model, but it is there. For example, if you did add that accessor property to the $appends array on the model:

public $appends = [
    'location_site'
];

And dumped dump($location->toArray());, you will see it.

Please or to participate in this conversation.