Laravel - How to display all posts related to category

I have to make category in post, but i have an error:

Trying to get property 'id' of non-object (View: C:\xampp\htdocs\klikdesaku\resources\views\home.blade.php)

If i click category, I want to display all posts related to category

this is my model Post.php:

public function category(){
   return $this->belongsTo(Category::class);
}

Category.php:

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

home.blade.php:

<h5 class="card-header">Categories</h5>
  <div class="card-body">
    <div class="row">              
        @foreach($categories as $category)
        <div class="col-lg-6">
          <ul class="list-unstyled mb-0">
            <li>
             <a href="{{$category->post->id}}">{{$category->name}}</a>
            </li>
          </ul>
        </div>
        @endforeach
    </div>
  </div>

Upvotes: 0

Views: 1895

Answers (2)

Abrar Ahmad
Abrar Ahmad

Reputation: 430

Because Category has hasMany relationship with Post, you have to fetch the posts first and then get data of the post. Something like this.

$categories = Category::with('posts')->get();

@foreach($categories as $category)
    @foreach($category->posts as $post)
        <ul>
            <li>
                <a href="{{ $post->id }}">{{ $post->title }}</a>
            </li>
        </ul>
    @endforeach
@endforeach

Upvotes: 1

Fer Toasted
Fer Toasted

Reputation: 1738

You will have to use a nested loop which is not the best idea if your app is big, but for a small project it will do the job.

@foreach($categories as $category)
    @foreach($category->posts as $post)
        <ul>
            <li>
                <a href="{{ $post->id }}">{{ $category->name }}</a>
            </li>
        </ul>
    @endforeach
@endforeach

Upvotes: 0

Related Questions