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

在闭包中使用父函数参数

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 2013-06-24 14:39
    关注

    Try a use() clause:

    return Auth::user()->sessions->filter(function($session) use( $slug)
    {
        return $session->slug == $slug;
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了