【问题标题】:Calling variables to sub function? [duplicate]调用子函数的变量? [复制]
【发布时间】:2018-05-19 16:24:35
【问题描述】:

我有一个 post 变量,我想将它用作我的子函数。我怎样才能做到这一点 ?当我尝试时,它显示“未定义的变量”。

控制器

public function getSingle($slug){

    $post = Post::where('slug',$slug)->first();

    $related_categories_posts = Post::whereHas('categories',function ($query){
        $query->where('category_name', $post->categories->category_name);
    })
    ->take(3)
    ->get();



    return view('frontend.single')
            ->with('post',$post)
            ->with('related_categories_posts',$related_categories_posts);
}

有什么建议吗?

【问题讨论】:

  • 我建议您修复代码缩进问题。
  • 你没有use
  • @revo 好像是这样,我找不到它..

标签: php function variables laravel-5 laravel-5.5


【解决方案1】:

您需要使用use 将这个变量传递给函数,如docs 中所述。

$related_categories_posts = Post::whereHas('categories', function ($query) use ($post){
    $query->where('category_name', $post->categories->category_name);
})

【讨论】:

  • 它有效,谢谢。我不知道
猜你喜欢
  • 2013-12-31
  • 1970-01-01
  • 2015-10-25
  • 2011-03-23
  • 2021-09-18
  • 1970-01-01
  • 2013-01-30
  • 2020-01-10
  • 2013-02-06
相关资源
最近更新 更多