1

I have following code:

In a Category Model

public function posts()
{
  return $this->belongsToMany(Post::class, 'post__post_category_relations', 'category_id');
}

public function children()
{
  return $this->hasMany(Category::class, 'parent_id');
}

In a Category Controller:

public function index(Category $category){
  $category_childrens = $category->children;
  $posts = ???;
  return view('show.posts',compact('posts'));
}

I am trying to retrieve the $posts associated with $category_childrens and pass them to my view.

lufc
  • 1,965
  • 2
  • 15
  • 19
justcntt
  • 197
  • 1
  • 2
  • 12

1 Answers1

0

I found solution in here:

Laravel get all products from infinity nested categories

My script:

In a Category Model:

public static function getAllPosts($category, $posts = null)
{
    if ($posts == null) {
        $posts = collect();
    }
    $posts = $posts->merge($category->posts);

    foreach($category->children as $child){
        $posts = self::getAllPosts($child, $posts);
    }

    return $posts;
}

In a Controller:

....
$category = $this->category->findBySlug($_GET['category_name']);

$posts = Category::getAllPosts($category);

return view('post::admin.posts.index', compact('posts','category','categories'));
justcntt
  • 197
  • 1
  • 2
  • 12