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

serhiiposternak's avatar

Laravel query issue

I need your help. I try to do this query:

     public function future_trips($cat_id, $city_id)
        {
            $trips=Events::where('start_date','>',Carbon::now()->subDay(5))
                ->where(function ($q)
                {
                    $q->where('category_id',$cat_id)->orWhere('city', $city_id);
                })
                ->get();
}

__ ErrorException: Undefined variable: cat_id in file C:\x......

Undefined variable $cat_id less... (Ctrl+F1) The inspection can produce two types of warnings: The definition of the variable can not be found anywhere. ("Undefined variable") There are one or more paths to reach the line with the variable usage without defining it. ("Variable might have not been defined") __

Can somebody explain me why ?

0 likes
2 replies
tisuchi's avatar
tisuchi
Best Answer
Level 70

@serhiiposternak

If you are having undefined variable error, then you need to add these variables to the function closure with use. Php does not automatically include variables outside the closure.

public function future_trips($cat_id, $city_id)
{
    $trips = Events::where('start_date', '>', Carbon::now()->subDay(5))
        ->where(function ($q) use ($cat_id, $city_id)
        {
            $q->where('category_id',$cat_id)->orWhere('city', $city_id);
        })
        ->get();
}

I believe it will work.

10 likes

Please or to participate in this conversation.