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

naykel's avatar

Query builder wont accept variable

Can anyone tell me why I can not get the sub query in the function to accept the $slid parameter I pass in when calling the method?

public static function scopeNav($q, $scid, $slid)
{
    return $q->where('id', $scid)
        ->with('studentLessons', function ($q1) use ($slid) { // i have included here
            $q1->where('is_locked', false)
                ->where('id', '>', $slid)->dump();
        })->get();
}

If I manually the value the query works fine but for some reason I can't get it accept the parameter I pass it in even though i know the value is correct.

0 likes
6 replies
Sinnbeck's avatar

What error do you get? And how do you use the scope?

tykus's avatar

I can't get it accept the parameter

What is the nature of the failure; how are you determining that the value is not accepted?

Aside, your scope is malformed; it should be a public instance method, not static, and it should not complete the query

public function scopeNav($q, $scid, $slid)
{
    return $q->where('id', $scid)
        ->with('studentLessons', function ($q1) use ($slid) {
            $q1->where('is_locked', false)
                ->where('id', '>', $slid)->dump();
        });
}

https://laravel.com/docs/8.x/eloquent#local-scopes

tykus's avatar

@Sinnbeck very true, although the docs always show a return, so consistency 🤷‍♂️

1 like
naykel's avatar

@tykus sorry I did not really explain well,

public function scopeNav($q, $scid, $slid)
{
    // if you dump the $scid here you get a value of 4877
    // dd($scid) value = 4877
    return $q->where('id', $scid)
    ->with('studentLessons', function ($q1) use ($slid) {
        $q1->where('is_locked', false)
                // here is the problem the $slid value is not being read in and it returns empty
                ->where('id', '>', $slid); 
        })->get();
}

However, If i take the exact same method and manually enter the value then the query works as expected

public function scopeNav($q, $scid, $slid)
{
    return $q->where('id', $scid)
    ->with('studentLessons', function ($q1) use ($slid) {
        $q1->where('is_locked', false)
                // and manually type 4877, it returns 'studentLessons' as expected
                ->where('id', '>', 4877);
        })->get();
}

so the problem in not that the query does not work it is that it won't accept the $scid parameter I pass in.

Hope that makes more sense.

SilenceBringer's avatar
Level 55

@naykel your problem is here

->with('studentLessons', function ($q1) use ($slid) {

it must be

->with(['studentLessons' => function ($q1) use ($slid) {

}])
2 likes

Please or to participate in this conversation.