1

I have a global variable that I need to pass to my query:

$size = (user input)

$name = (user input)

$items = Items::with('color')->with(['size' => function ($query){

                $query->where('meters', '=', $size);
            }])

                ->where('item_name', '=', $name)
                ->get();

The problem with this query is that the $color variable is not available in the closure: I really need to eager load the data instead of joining tables as I already defined a variable that is used in the view. How can I pass that variable to the closure?

Chriz74
  • 1,410
  • 3
  • 23
  • 47

2 Answers2

1

How about

$size = '(size value)';
$items = Items::with('color')
    ->whereHas('size', function ($query) use ($size) {
        $query->where('meters', $size);
    })
    ->where('item_name', $name)
    ->get();
alepeino
  • 9,551
  • 3
  • 28
  • 48
0

You just pass it to your function.

$items = Items::with('color')->with(['size' => function ($query, $size) {

            $query->where('meters', '=', $size);
        }])

            ->where('item_name', '=', $text)
            ->get();
Can Celik
  • 2,050
  • 21
  • 30
  • 1
    doesn't work, it throws this error: Missing argument 2 for App\Http\Controllers\ItemController::App\Http\Controllers\{closure}() – Chriz74 Mar 02 '16 at 18:55
  • Oh wait sorry I misread the code. where does $color comes or defined? – Can Celik Mar 02 '16 at 19:03
  • don't worry about the color. I made an error writing the code in the question. I updated it. I need to pass $size to the closure – Chriz74 Mar 02 '16 at 19:04
  • If the size is already defined then you can just pass it to your function as the first answer. If it's defined somewhere else as global then you should declare it global as in this answer http://stackoverflow.com/questions/5449526/cant-access-global-variable-inside-function – Can Celik Mar 02 '16 at 19:07
  • the problem with this query is that it's returning data also if meters is not equal $size ... – Chriz74 Mar 02 '16 at 19:20