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

mecjos's avatar

Using Global Variable in Eloquent Model Query

Hi. I am trying to use a variable where is outside of model query inside it as following codes but it doesn't work. Normally I can use it inside function by making global..

public function setPriority ($id) {
        $affectingJob = Job::find($id);
        $machine_id = 1;
        $affectedJobQueue = Job::where([['state_id', 1],['user_id', Auth::user()->parent_user_id]])->with(['order' => function ($query) {
            global $machine_id;
            $query->where('machine_id', $machine_id);
        }])->get()->min('queue');

what's the problem in my code??

0 likes
4 replies
deepu07's avatar
deepu07
Best Answer
Level 11

@mecjos try this

public function setPriority ($id) {
        $affectingJob = Job::find($id);
        $machine_id = 1;
        $affectedJobQueue = Job::where([['state_id', 1],['user_id', Auth::user()->parent_user_id]])->with(['order' => function ($query) use ($machine_id) {
            $query->where('machine_id', $machine_id);
        }])->get()->min('queue');

martinbean's avatar

@mecjos You shouldn’t be using global variables like this. That suggests you’re doing something that could be done in a much better way.

Can you explain what it is you’re actually trying to do, and not how you’re trying to do it?

Snapey's avatar

Pretend you never heard of global variables - they were for your dad's php

OK, with no globals available to you, what are your options? Well it depends on when and where you need to set this scope?

Please or to participate in this conversation.