I want to show posts that are in a category by clicking on them, but when I click on a category,$articles
in category.blade.php
returns null.
$articles
should return articles that have a specific category
this is my index.blade.php
:
<div id="show-categories" role="tabpanel">
<h6 >Categories</h6>
<div >
@foreach($categories as $category)
<div >
<a href="{{ route('cms.category', $category->id) }}">
{{ $category->name }}
</a>
</div>
@endforeach
</div>
</div>
category.blade.php
:
@extends('layouts.app')
@section('content')
@forelse ($articles as $article)
<h1>{{$article->title}}</h1>
@empty
<span>array is empty</span>
@endforelse
@endsection
router
:
Route::get('cms/categories/{category}', [articlesController::class, 'category'])->name('cms.category');
and articlesController
:
public function category(Category $category)
{
return view('cms.category')
->with('category', $category)
->with('articles', $category->articles()->searched()->simplePaginate(3))
->with('categories', Category::all())
->with('tags', Tag::all());
}
CodePudding user response:
Please, don't forget to define the relationship from Category to Article on your model. Like: one category has many articles. For example:
On your Category.php model:
public function articles()
{
return $this->hasMany(Article::class);
}
Then on your, controller, you may call the relationship like this way:
public function category(Category $category)
{
$articles = Category::with("articles")->where("id", $category->id)->simplePaginate(3);
return view('cms.category')
->with('category', $category)
->with('articles', $articles)
->with('categories', Category::all())
->with('tags', Tag::all());
}
CodePudding user response:
Please share the model file and second I prefer to write the category method in a different way.
public function category($category_id)
{
try {
$articles= Article::where('id', $category_id)->get();
return view('cms.category', $articles);
} catch (\Throwable $th) {
Log::error($th->getMessage());
}
}
Let me know if you still face any issue. Try to use dd $articles ..