1
votes

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.

enter image description here

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

1
I think that you need to ->orWhere('parent_id', null) instead of ->orWhere('depth', null)hassan
Hello @hassan, I've edit my question. My request is a little different nowJeremy
both parent() and children() are pointing to the same Model CategoryYash Lotan

1 Answers

0
votes

You can get parent category's name from child category by

$category->parent()->name

Also I think you copy pasted the child function to parent function. Change the Model, which currently point to App\Models\Category in both parent and child.