Reputation: 780
I'm using Laravel 5.3's query builder, trying to add a where clause to find articles with a certain tag:
$tag_list = $request->tag_list; // tag_list is an array
if (isset($tag_list)) {
foreach ($tag_list as $tag_id) {
$query = $query->whereHas('tags', function ($query) {
$query->where('id', $tag_id);
});
}
}
When I dump $tag_list I get...
24
But in the loop, I get an error:
Undefined variable: tag_id
What am I doing wrong? Any help is appreciated!
Upvotes: 2
Views: 786
Reputation: 2152
Because you are in function context. Pass tag_id variable via - use keyword
$tag_list = $request->tag_list; // tag_list is an array
if (isset($tag_list)) {
foreach ($tag_list as $tag_id) {
$query = $query->whereHas('tags', function ($query) use ($tag_id) {
$query->where('id', $tag_id);
});
}
}
Upvotes: 7