I try to get the category from my article.
A category can have several sub categories, but I only want the first level. In my DataBase, each sub categories has a parent_id, stored in the same table.
I have a method scopeFirstLevelItems but I don't think it will help me here?
public function scopeFirstLevelItems($query)
{
return $query->where('depth', '1')
->orWhere('depth', null)
->orderBy('lft', 'ASC');
}
It's possible to get the category parent from the sub categories ?
For get the category in my controller, I try this
protected function index(Article $article)
{
$articles = Article::published()->paginate(8);
$category = Category::with('articles')->firstLevelItems()->where('id', $article->id)->get();
return view('pages.blog', [
'articles' => $articles,
'category' => $category
]);
}
And in my view
<a href="{{ $category->slug }}">{{ $category->name }}</a>
But it doesn't work.
And I have three relations in my Category model
public function parent()
{
return $this->belongsTo('App\Models\Category', 'parent_id');
}
public function children()
{
return $this->hasMany('App\Models\Category', 'parent_id');
}
public function articles()
{
return $this->hasMany('App\Models\Article');
}
Can you help me ? Thank you
->orWhere('parent_id', null)
instead of->orWhere('depth', null)
– hassanparent()
andchildren()
are pointing to the same ModelCategory
– Yash Lotan