-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(); 
4
  • 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. Commented Jul 15, 2021 at 20:51
  • yes, It says undefined variable Commented Jul 15, 2021 at 20:54
  • Read here about anonymous functions in php. Check out example #3 on inheriting variables from the parent scope Commented Jul 15, 2021 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. Commented Jul 15, 2021 at 21:20

2 Answers 2

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(); 
Sign up to request clarification or add additional context in comments.

5 Comments

yes, Now its working fine. Thanks
@AbdulMoiz If it works for you, please mark the answer as accepted!
can you please guide me which jQuery event I can use to get the products between Prices using price range slider?
@AbdulMoiz I have no experience in frontend development, sorry bro.
How can I show products using Load More Button instead of pagination. any idea?
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(); 

2 Comments

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.
@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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.