2

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!

2
  • 24 is not an array. Commented Jan 22, 2017 at 16:23
  • Are you sure that $tag_list is an array? If all you're getting back from a var_dump is 24 it looks like that var is a string or int. Commented Jan 22, 2017 at 16:25

1 Answer 1

7

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

2 Comments

Ahhh I remember that now from a Laracasts tutorial... thanks @vuliad
For reference, also see php.net/manual/en/functions.anonymous.php, "Example #3 Inheriting variables from the parent scope".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.