我想說明,在一個類別通過點擊帖子,但是當我點擊一個類別,$articles在category.blade.php回傳null。
$articles 應該回傳具有特定類別的文章
這是我的index.blade.php:
<div class="tab-pane fade" id="show-categories" role="tabpanel">
<h6 class="sidebar-title">Categories</h6>
<div class="row link-color-default fs-14 lh-24">
@foreach($categories as $category)
<div class="col-6">
<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');
和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());
}
uj5u.com熱心網友回復:
請不要忘記在您的模型上定義從類別到文章的關系。喜歡:一個類別有很多文章。例如:
在您的Category.php模型上:
public function articles()
{
return $this->hasMany(Article::class);
}
然后在您的控制器上,您可以這樣呼叫關系:
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());
}
uj5u.com熱心網友回復:
請分享模型檔案,其次我更喜歡以不同的方式撰寫類別方法。
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());
}
}
如果您仍然面臨任何問題,請告訴我。嘗試使用 dd $articles ..
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/394015.html
標籤:拉拉维尔
