douduan5753
douduan5753
2013-06-24 14:38
浏览 56
已采纳

在闭包中使用父函数参数

I'm trying to use a parameter that is passed through to resource controller action in Laravel 4 in a closure that is filtering a model collection, however I get the error below:

Undefined variable: slug

How can I pass through the $slug parameter from the route through to the collection filter closure?

public function show($slug)
{
    return Auth::user()->sessions->filter(function($session)
    {
        return $session->slug == $slug;
    });
}

All I am trying to achieve is to return the session of the user that matches the given slug. I've tried something like this to no avail:

Auth::user()->sessions->whereSlug($slug);
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dongyan3018
    dongyan3018 2013-06-24 14:39
    已采纳

    Try a use() clause:

    return Auth::user()->sessions->filter(function($session) use( $slug)
    {
        return $session->slug == $slug;
    });
    
    点赞 评论
  • dongyan1491
    dongyan1491 2013-06-24 14:43

    The second attempt I used (instead of a filter) did not work because I was using an Eloquent method on what is essentially a Fluent (query builder) interface. It could be fixed as such:

    Auth::user()->sessions->where('slug', '=', $slug)->first();
    

    Posting this as it may be helpful to others.

    点赞 评论

相关推荐