0

I have a post variable and I want to use it my sub function. How can I do that ? When I tried it says "Undefined Variable".

Controller

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);
}

Any advice ?

SamHecquet
  • 1,818
  • 4
  • 19
  • 26

1 Answers1

0

You need to pass this variable to the function by using use as described in the docs.

$related_categories_posts = Post::whereHas('categories', function ($query) use ($post){
    $query->where('category_name', $post->categories->category_name);
})
SamHecquet
  • 1,818
  • 4
  • 19
  • 26