0

I have the following relationship built in my app between two models.

Post.php

public function category()
{
    return $this->belongsTo('App\Category', 'category_id')->withDefault();
}

Category.php

public function post()
{
    return $this->hasMany('App\Post', 'category_id');
}

I want to get the data in the following format in my view:

  1. Category Title 1

    • Post Title 1
    • Post Title 2
    • Post Title 3
  2. Category Title 2

    • Post Title 1
    • Post Title 2
    • Post Title 3
  3. Category Title

    • Post Title 1
    • Post Title 2
    • Post Title 3

Controller

$posts = Post::all();
$categories = $posts->pluck('category')->unique();

View/Blade

@foreach($categories as $category)
    {{  $category->name }}
    @foreach($category as $item)
        {{  $item->post->name }}
    @endforeach
@endforeach

It's not working. I am looking forward to any suggestions.

2 Answers 2

0

I think it's better to use plural form for your manyToMany method name (postsinstead of post), but with current situation this code should work:

 @foreach($categories as $category)
      {{$category->name}}
      @foreach($category->post as $item)
        {{$item->title}}
     @endforeach
  @endforeach`   
0

Change relationship.Add foreign key in relationship.You don't have to select categories and posts in different variables.Relationship will get all datas if you properly assigned them.

public function category()
{
    return $this->belongsTo('App\Category', 'category_id','category_id');
}
public function post()
{
    return $this->hasMany('App\Post', 'category_id','category_id');
}
$categories = Category::all();

In view

@foreach($categories as $category)
 {{$category->name}}
 @foreach($category->post as $post)
    {{$post->title}}
 @endforeach
@endforeach

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.