Answer the question
In order to leave comments, you need to log in
Why aren't posts in each category displayed?
For some reason, posts are not displayed on the category page. I can only get the number of posts, not the posts themselves.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
use HasFactory;
public function posts(){
return $this->hasMany(Post::class);
}
}
public function getCategory($slug){
$category = Category::where('slug', $slug)->first();
return view('blog.category', compact('category'));
}
@extends('layouts.app')
@section('title')
{{ $category->name}}
@endsection
@section('content')
<h1>{{ $category->name }}</h1>
<h3>{{ $category->posts()->count() }}</h3>
@foreach($category->posts() as $post)
<h5>{{ $post->title }}</h5>
@endforeach
@endsection
Answer the question
In order to leave comments, you need to log in
@foreach($category->posts as $post)
Also remember to read https://laravel.com/docs/8.x/eloquent-relationship... and https://laravel.com/docs/8. x/eloquent-relationship...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question