david19's avatar

Category_Slug for Subviews

Hello Team, sorry for the question again, but i tryed many hours before :)

ID 1: Cars = parent_id = NULL
ID 2: BMW = parent_id = 1
ID 3: Ford = parent_id =  1
ID 4: Bikes = parent_id = NULL
ID 5: Cross-Bike = parent_id = 4

With this Line i get all subcategories with the id.

public function subcategories($id)
    {
      $categories = category::where('parent_id',$id)->get();
      return $categories;

    }
localhost/shop/1
0   
id  2
name    "BMW"
parent_id   1
category_slug   "bmw"
created_at  "2019-11-21 00:00:00"
updated_at  "2019-11-21 00:00:00"
1   
id  3
name    "Ford"
parent_id   1
category_slug   "ford"
created_at  "2019-11-21 00:00:00"
updated_at  "2019-11-21 00:00:00"

Instead of ID, i like the category_slug "cars".

localhost/shop/cars
Route::get('/shop/{category_slug}', 'Shop\Product\ProductCategoryController@subcategories')
public function subcategories($category_slug)
    {
      $categories = category::where('parent_id',$category_slug)->get();
      return $categories;

    }

I get nothing :(

0 likes
4 replies
Nakov's avatar
Nakov
Best Answer
Level 73

@david19 because the column is not parent_id but category_slug so you should use this instead:

      $categories = category::where('category_slug',$category_slug)->get();

Also if you are changing the default route key name you should tell laravel that by overriding the method..

so in your model add this:

public function getRouteKeyName() 
{
    return 'category_slug';
}
1 like
david19's avatar

Thanks Nakov, i know. But now i get only "cars" without Subcategories.

localhost/shop/cars
0   
id  1
name    "Cars"
parent_id   null
category_slug   "cars"
created_at  "2019-11-21 00:00:00"
updated_at  "2019-11-21 00:00:00"

But i need all subcategories in cars.

0   
id  2
name    "BMW"
parent_id   1
category_slug   "bmw"
created_at  "2019-11-21 00:00:00"
updated_at  "2019-11-21 00:00:00"
1   
id  3
name    "Ford"
parent_id   1
category_slug   "ford"
created_at  "2019-11-21 00:00:00"
updated_at  "2019-11-21 00:00:00"

That is the problem if i use RouteKeyName :(

david19's avatar

I think this works:

 $categories = category::where('category_slug',$category_slug)->with('categories')->get();
Nakov's avatar

@david19 in your category model you can add your relationship like this:

public function subcategories()
{
    return $this->hasMany(Category::class, 'parent_id', 'id');
}   

Then when you use it:

Category::where('category_slug', $category_slug)->with('subcategories')->get();

This should work.

1 like

Please or to participate in this conversation.