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

Alizey's avatar

Date Fetch Problem From A Relation

i having two table category and sub category Category Model function

public function sub_cats()
{
        return $this->hasMany('App\Sub_Category');
}

Sub Category Model Function

public function category()
{
        return $this->belongsTo('App\Category');
}

Now at my view i want to show category with their sub categories My View Function

public function view()
    {
        $view = Sub_Category::has('category')->OrderBy('id','DESC')->paginate(15);
        return view('backend.sub_categories.view')->with('viewCats',$view);
    }

@ my view i want to show

<th> Sub Category </th>
<th> Category Name </th>

 @if($viewCats->count() > 0)
      @foreach($viewCats as $cats)
      <tr>
       <td><a href="#">{{$cats->sub_catname}}</a></td>
       <td>
        @foreach ($cats->category as $cat)
         {{ $cat->category_name }}
         @endForeach
         </td>
      </tr>

Why i don't got the category name ? Every thing else is working fine

0 likes
2 replies
RachidLaasri's avatar

If a sub-category belongs to a parent category, the why using the foreach?

Sonu's avatar

@Alizey instead of inner foreach just use

 {{$cats->category->category_name}}

its definately works :D

Please or to participate in this conversation.