Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

saadat_2003's avatar

Display sub categories under a particular category clicked from homepage

any one help me as I have displayed categories(categories table) name on index using index function , $categories = Category::all()->toArray(); return view('index', compact('categories')); I want to make the names of categories as clickable links when user click on a categoey he will go to single page where all the subcategories(from sub categories table) of that particular clicked category should shown

0 likes
19 replies
saadat_2003's avatar

@tisuchi I have written this code in header.blade.php . what would be the href for me in this line href="/category/{{ $category->id }}"

RamjithAp's avatar

Use URL helper so that your link will not break when you use it common header file.

<a href="{{ url('category')}}/{{ $category->id }}">{{ $category->name }}</a>
saadat_2003's avatar

@RamjithAp thanks for ur help , I have table of categories_sub ,I have category id in sub category table .Now I want to display sub categories for a specific category link which is clicked

RamjithAp's avatar

Go to your App/Categories.php model and write

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Categories extends Model
{
    /**
     * Get the comments for the blog post.
     */
    public function subcategories()
    {
        return $this->hasMany('App\SubCategories','foreign_key_column_name');
    }
}

Also in App/SubCategories.php model

public function categories()
{
    return $this->belongsTo('App\Categories','id');
}

Then in your controller

$category =  Category::find($id);
$subcategories= Category::find($id)->subcategories;

return view('index')->withCategory($category)->withSubcategories($subcategories); 

And In your view

@foreach($subcategories as subcategory)
     <span>{{ $subcategory->name}}</span>
@endforeach

For more details read https://laravel.com/docs/5.5/eloquent-relationships#one-to-many

saadat_2003's avatar

@RamjithAp any idea about this Property [subcategories] does not exist on this collection instance.

RamjithAp's avatar

I guess you are trying this way

@foreach($category->subcategories as subcategory)

Try this (if you using my above samples)

@foreach($subcategories as $subcategory)
RamjithAp's avatar

No man! if you sending category & subcategory to view like the way I suggested above then use.

@foreach($subcategories as $subcategory)
saadat_2003's avatar

@RamjithAp kindly tell me about best tutorial in laravel 5.5 that would help me in completing this task .I just want to display subcategories on single detail page under the category which is clicked from index page .kindly help me as I am trying to do this since last week

RamjithAp's avatar

Wait, show me your route, controller, modal, view file codes I will tell whats wrong with your code. Problem is you are not pasting your codes so its difficult to figure out your mistake.

1 like
RamjithAp's avatar
Level 10

Okay, so I have reviewed your code & following things need to be corrected.

1 . Line number 101, wrong variable definition change this

 @foreach($subcategories as SubCategory)
            <h1 class="f22 gr">{{ $subcategory->csname}}</h1>
 @endforeach

To this

 @foreach($subcategories as $subcategory)
            <h1 class="f22 gr">{{ $subcategory->csname}}</h1>
 @endforeach

2 . line number 109, there is some extra character remove it

Route::get('search-categories/{cid}', 'SubCatController@index');

3 . Line number 43, you have not passing the $cid parameter.

 public function index($cid)
    {
       $category =  Category::find($cid);
       $subcategories= Category::find($cid)->subcategories;
       return view('search-categories')->withCategory($category)->withSubcategory($subcategories);
    }

4 . Last but not least you must set column 'cid' as foreign key in order to use laravel relationships. So you have two options now, one is set cid as FK or use direct DB class to get subcategories.

First option, make cid as Fk like this

ALTER TABLE categories_sub
ADD CONSTRAINT FK_cid
FOREIGN KEY (cid) REFERENCES categories(cid);

Second option, If you cant set foreign key go to your SubCatController.php change code like below.

    public function index($cid)
    {
       $category =  Category::find($cid);
       $subcategories= SubCategory::where('cid',$cid)->get();
       return view('search-categories')->withCategory($category)->withSubcategories($subcategories);
    }

All the best! let me know if you still facing any issues.

saadat_2003's avatar

thanks bro @RamjithAp , You have helped out very much ,I have also learned very much. I have created foreign key relationship. Now getting this error, but their is no id column SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause' (SQL: select * from categories where id = 17 limit 1)

saadat_2003's avatar

I have set protected $primaryKey = 'cid'; in category model .Now that error is not showing but when i write this in controller return $subcategories; it gives correct [{"csid":35,"cid":17,"csname":"Civic","csStatus":null}] but on this gives error Undefined variable: subcategories (View: C:\xampp\htdocs\carzhub\resources\views\search-categories.blade.php) Again Thanks for your help @RamjithAp

RamjithAp's avatar

Issue is in this line ->withSubcategory($subcategories);

  public function index($cid)
    {
       $category =  Category::find($cid);
       $subcategories= SubCategory::where('cid',$cid)->get();
       return view('search-categories')->withCategory($category)->withSubcategory($subcategories);
    }

Change to this

  public function index($cid)
    {
       $category =  Category::find($cid);
       $subcategories= SubCategory::where('cid',$cid)->get();
       return view('search-categories')->withCategory($category)->withSubcategories($subcategories);
    }

And now in your views

 @foreach($subcategories as $subcategory)
            <h1 class="f22 gr">{{ $subcategory->csname}}</h1>
 @endforeach
saadat_2003's avatar

Its solved .Thanks a lot friend .you have helped a lot

saadat_2003's avatar

@foreach($category->subcategories as $subcategory)

{{ $subcategory->csname}}

@endforeach

and then I have set protected $primaryKey = 'cid'; in category model then error resolved Also add this to your reply that I have accepted @RamjithAp

saadat_2003's avatar

The query is working correctly in mysql .I want to write it in my controller. @tisuchi @RamjithAp

SELECT cname FROM categories where cid IN(SELECT max(category) FROM items group by category order by category desc ) order by cid desc LIMIT 10

Please or to participate in this conversation.