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条)

报告相同问题?

悬赏问题

  • ¥50 随机森林与房贷信用风险模型
  • ¥50 buildozer打包kivy app失败
  • ¥30 在vs2022里运行python代码
  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误
  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备