T
T
Tech52020-05-22 18:37:42
Laravel
Tech5, 2020-05-22 18:37:42

How to correctly display a child category by alias from the URL?

Dear Khabrovites, please tell me how to correctly display the contents of a child category by alias from the URL?

I have two tables categories and subcategories which have "id" columns, the subcategories table also has a category_id foreign key associated with the id in the categories table.

There are also two models:

class Category extends Model
{
    public function subcategory()
    {
        return $this->hasMany('App\Subcategory');
    }
}

class Subcategory extends Model
{
    public function category()
    {
        return $this->belongsTo('App\Category')->category_id;
    }
}

In the controller SubcategoryController I specify:
class SubcategoryController extends Controller
{
    public function show(Subcategory $subcategory)
    {
        $subcategory = Subcategory::find($subcategory);
        return view('dashboard.subcategories.show', compact('subcategory'));
    }
}

At the output, I get not only the desired Child category belonging to the Parent category, for example with id = 5, but also another Child category with the same id = 5.

How can I display only one child category I need in the show function by alias from the URL?
Thank you in advance!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
Tech5, 2020-05-23
@Tech5

Lost a little, it was necessary to leave it like this:

class SubcategoryController extends Controller
{
    public function show(Subcategory $subcategory)
    {
        return view('dashboard.subcategories.show', compact('subcategory'));
    }
}

E
ediboba, 2020-05-22
@ediboba

Something like this:
Subcategory::find($id)->category

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question