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

someUser's avatar

Eager loading where query returns empty array

Hi there,

i am having a small issue with a where query on a relation. When ever i try to get $courses, it returns an empty array - however, if i dump the same query i'll receive the desired results.

dd($query->where('businessunit', $queryParams['filterByBusinessUnitShortName'])->get());

Here is the controller where the query is being used.

//CourseController.php

$queryParams = $request->query();

$courses = Course::whereHas('siteObject', function ($query) use ($queryParams) {
$query->where('businessunit',$queryParams['filterByBusinessUnitShortName']);
 })->get();

return $courses;

Relation on the course class

//Course class
public function siteObject() {
    return $this->belongsTo(Site::class, 'site');
}

Could anyone point me the issue here?

0 likes
3 replies
goldtaste's avatar

Try

$site = Site::where('businessunit',$queryParams['filterByBusinessUnitShortName'])->with('courses')->first();

return $site->courses;
Snapey's avatar

siteObject belongs to Site, but you are using Course

How does siteObject relate to Course in order for it to be eager loaded?

goldtaste's avatar

Just realised my query will only work if you only have one businessunit for a site. Can multiple sites have the same businessunit?

I think your query looks fine (get me all courses that are linked to any sites that have a businessunit named x)

Have you tried running the sql against the db:

dd(Course::whereHas('siteObject', function ($query) use ($queryParams) {
$query->where('businessunit',$queryParams['filterByBusinessUnitShortName']);
 })->toSql());

Are you sure that the sites in question definitely have courses?

In your site model do you have the following method:

 public function courses()
    {
        return $this->hasMany('App\Course');
    }

Please or to participate in this conversation.