1

First time working with eloquent relationship. I'm trying to access the subcategory method yet I get this error:

Property [subcategory] does not exist on this collection instance.

New to laravel so any help would be appreciated!

blade

                <table class="table">
                    <thead>
                        <tr>
                            <th scope="col">Category</th>
                            <th scope="col">Sub-category</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach ($categories as $cat)
                            <tr>
                                <td scope="row">{{$cat->name}}</td> 

                                 //error here
                                @foreach ($categories->subcategory as $item)
                                    <td>{{$item->name}}</td>
                                @endforeach

                            </tr>
                            @endforeach
                    </tbody>
                </table>

category model

class Category extends Model
{
protected $fillable = ([
    'name'
]);

public function subcategory(Type $var = null)
{
    # code...
    return $this->hasMany(Subcategory::class,'category_id','id');
}
}

subcategory model

class Subcategory extends Model { protected $fillable = ([ 'category_id', 'name' ]);

public function category(Type $var = null)
{
    # code...
    return $this->belongsTo(Category::class);
}
}

controller

public function create()
{
    $categories = Category::all();
    // dd($categories);
    return view('settings.create', compact('categories'));
}
kwestionable
  • 496
  • 2
  • 8
  • 23
  • Does this answer your question? [Property \[title\] does not exist on this collection instance](https://stackoverflow.com/questions/41366092/property-title-does-not-exist-on-this-collection-instance) – miken32 Apr 16 '21 at 15:22

3 Answers3

4

You are doing wrong in foreach loop. Your second foreach loop will be like

@foreach ($categories as $cat)
    <tr>
        <td scope="row">{{$cat->name}}</td> 
        @foreach ($cat->subcategory as $item)
        <td>{{$item->name}}</td>
        @endforeach

    </tr>
@endforeach

your current object is $cat and $categories is a collection.

zahid hasan emon
  • 6,023
  • 3
  • 16
  • 28
2

You are calling subcategory of $categories collection not on one model $cat. So change your @foreach method to

@foreach ($cat->subcategory as $item)
   <td>{{$item->name}}</td>
@endforeach
Gopal Kildoliya
  • 649
  • 5
  • 21
0

My solution:

 @foreach ($cat->subcategory as $item)        
    <td>{{$item->name}}</td>    
 @endforeach
Saeed
  • 3,294
  • 5
  • 35
  • 52