Mikkel Winther
Mikkel Winther

Reputation: 597

Laravel 4 Controller parameter scope

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?

Upvotes: 0

Views: 669

Answers (1)

JustinHo
JustinHo

Reputation: 4745

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.

Upvotes: 1

Related Questions