0

Could you help me figure out why this code does not work:

public function getByTag($slug) {

    $posts = Post::whereHas('tags', function($q) {
        $q->where('slug', '=', $slug);
    })->paginate(5);

    return View::make('home')->with('posts', $posts);

}

When this does:

public function getByTag($slug) {

    $posts = Post::whereHas('tags', function($q) {
        $q->where('slug', '=', 'test');
    })->paginate(5);

    return View::make('home')->with('posts', $posts);

}

I simply replaced the $slug in the where() method, because the page breaks with an error saying that $slug is undefined. If I kill the page with die($slug) it returns the correct value, and if, as in my second example, I swap the variable for a static slug value, the page loads the correct posts.

Is $slug inaccesible because I'm in a function that takes new parameters?

1 Answer 1

1
public function getByTag($slug) {

    $posts = Post::whereHas('tags', function($q) use ($slug) {
        $q->where('slug', '=', $slug);
    })->paginate(5);

    return View::make('home')->with('posts', $posts);

}

Add use ($slug) so $slug will be passed into.

Sign up to request clarification or add additional context in comments.

1 Comment

Spot on again. Thank you!

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.