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

haritz's avatar

Use variable inside query with

Hello, I have the next code on my controller:

public function week($league)
    {

        $user = auth()->user();

        $puntos = 0;

        $positions = array('top_id', 'jungle_id', 'mid_id', 'adc_id', 'sup_id');

        $league_id = League::where('LINK', $league)->firstOrFail(['id']);

        $weeks = Weeks::where('active', 1)->first();
        if (request('week') != null) {
            $week = request('week');
        } else {
            $week = Weeks::where('id', $weeks->id - 1)->first();
            $week = $week->name;
        }

        $roster = UserLeagueRoster::where([['user_id', $user->id], ['league_id', $league_id->id], ['WEEK', $week]])->first();


        if ($roster != null) {
            foreach ($positions as $posi) {
                $player = Player::with(['points' => function ($query) {
                    $query->where('WEEK', 'Week 4');
                }])->where('id', $roster->$posi)
                    ->get();

                foreach ($player as $points) {
                    $puntos += $points->points->sum('POINTS');
                }
            }
        }
        /*DB::table('user_league_roster')
            ->where([['user_id', $user->id], ['league_id', $league_id->id], ['WEEK', $week]])
            ->update(['points' => $puntos]);*/

        $league = UserLeagueRoster::where([['league_id', $league_id->id], ['WEEK', $week]])->orderBy('points', 'DESC')->get();

        $weeks = Weeks::all();

        return view('league\week', compact('roster', 'week', 'puntos', 'league', 'weeks'));
    }

In this part:

$player = Player::with(['points' => function ($query) {
                    $query->where('WEEK',  'Week 4');
                }])->where('id', $roster->$posi)
                    ->get();

Where is says "Week 4" I would like to use the variable $week but it says Undefined variable. How can I access to it?

Thank you.

0 likes
1 reply
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

To use a variable inside a closure (the anonymous function) you need to pass it in with use (kinda like you do with classes at the top of a class file)

$player = Player::with(['points' => function ($query) use ($week) {
     $query->where('WEEK',  $week);

Please or to participate in this conversation.