-1

How can I make this conditions with eloquent? I want all records with product and category table whose url_name equals to $variable_name.

Here is the code:

 \App\Product::with(['category' => function ($query) {

      $query->whereHas('url_name','Summer-Collection');
     
 }])->get();
Brian Thompson
  • 13,263
  • 4
  • 23
  • 43
  • Am I to assume you are getting an error about `$variable_name` not being defined? If so you will just need to add `use ($variable_name)` after the function parameters to put it within scope. If not, please add more detail to your question. Or even if that is the problem, include it in your question. – Brian Thompson Jul 15 '21 at 20:51
  • yes, It says undefined variable – Abdul Moiz Jul 15 '21 at 20:54
  • Read [here](https://www.php.net/manual/en/functions.anonymous.php) about anonymous functions in php. Check out example #3 on inheriting variables from the parent scope – Brian Thompson Jul 15 '21 at 20:55
  • 2
    Cleanest solution is `Product::with(['category' => fn($q) => $q->whereHas('url_name', $variable_name)])->get();` No need to import variables from parent scope with arrow functions. – miken32 Jul 15 '21 at 21:20

2 Answers2

0

Assuming that the url_name is on the category table, and you have a relation setup on the Product Model you would do something like this.

 $variable = 'Summer-Collection';

 \App\Product::with(['category'])->whereHas('category', function($query) use($variable) {
       $query->where('url_name','=',$variable);
 })->get();
Dharman
  • 30,962
  • 25
  • 85
  • 135
Abishek
  • 11,191
  • 19
  • 72
  • 111
  • You edited out a key part of their question, so I don't think this addresses the error that the OP is intending to ask about (well after an edit it does in passing..). I also don't think what they had was incorrect - [docs on constraining eager loads](https://laravel.com/docs/8.x/eloquent-relationships#constraining-eager-loads). – Brian Thompson Jul 15 '21 at 20:59
  • @BrianThompson, I realized that after I edited, but the query on the OP wouldn't work as `whereHas` works with relationships and cannot be used as a `where` clause. – Abishek Jul 15 '21 at 21:03
0

You just need to pass the variable to the closure using use:

$variable_name = "something";
\App\Product::with(['category' => function ($query) use($variable_name) {
    $query->where('url_name', $variable_name);
}])->get();
Mohsen Nazari
  • 1,281
  • 1
  • 3
  • 13