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

palla451's avatar

Query join error

I have this query

$duration = 1;

    $rooms = Room::Available($start,$end)
        ->where('pax', '=', $data['pax'])
        ->where('location','=',$data['location']) // Search in base alla sede
        ->join('prices',function ($join){
            $join->on('rooms.id','=','prices.room_id')
                ->where('prices.duration', '=', $duration);
        })->get();

And i have this error :

{message: "Undefined variable: duration", exception: "ErrorException",…}

but if my query is this , it's work

    $rooms = Room::Available($start,$end)
        ->where('pax', '=', $data['pax'])
        ->where('location','=',$data['location']) // Search in base alla sede
        ->join('prices',function ($join){
            $join->on('rooms.id','=','prices.room_id')
                ->where('prices.duration', '=', 1);
        })->get();

How how can I solve this problem , please .... help me!

0 likes
2 replies
lostdreamer_nl's avatar

You are using an anonymous function in there (in the join part) PHP Scopes will limit the visibility of any variable to the scope where it was declared ($duration was declared outside of that function)

You can tell the function to use the $duration variable like this:

$duration = 1;
$rooms = Room::Available($start,$end)
    ->where('pax', '=', $data['pax'])
    ->where('location','=',$data['location']) // Search in base alla sede
    ->join('prices', function ($join) use ($duration) {
        $join->on('rooms.id','=','prices.room_id')
            ->where('prices.duration', '=', $duration);
    })->get();
1 like

Please or to participate in this conversation.