Reputation: 13
$category = Category::orderBy('category_name_en', 'ASC')
->get();
$subcategory = SubCategory::where('category_id', $category->id)
->orderBy('subcategory_name_en', 'ASC')
->get();
$subsubcategory = SubSubCategory::where('subcategory_id', $subcategory->id)
->orderBy('subsubcategory_name_en', 'ASC')
->get();
return view('welcome', compact('category', 'subcategory', 'subsubcategory'));
In this above code we are getting error:
Property [id] does not exist on this collection instance.
Why is this error showing?
Upvotes: 0
Views: 633
Reputation: 3968
That's because you are returning a Collection whenever you write get
.
Try this instead:
$category = Category::orderBy('category_name_en', 'ASC')
->get();
$subcategory = SubCategory::whereIn('category_id', $category->pluck('id'))
->orderBy('subcategory_name_en', 'ASC')
->get();
$subsubcategory = SubSubCategory::whereIn('subcategory_id', $subcategory->pluck('id'))
->orderBy('subsubcategory_name_en', 'ASC')
->get();
return view('welcome', compact('category', 'subcategory', 'subsubcategory'));
The changes being where
converted to whereIn
, and ->id
becomes ->pluck('id')
.
As you can see from the documentation, whereIn
accepts an array of values for it's second argument, and pluck
will return an array of, in our case, IDs.
Combining these will mean that category_id
will need to exist within the array.
If, however, these models were supposed to supply a single Model.
Then you should do the following:
$category = Category::orderBy('category_name_en', 'ASC')
->first();
$subcategory = SubCategory::where('category_id', $category->id)
->orderBy('subcategory_name_en', 'ASC')
->first();
$subsubcategory = SubSubCategory::where('subcategory_id', $subcategory->id)
->orderBy('subsubcategory_name_en', 'ASC')
->first();
return view('welcome', compact('category', 'subcategory', 'subsubcategory'));
This is using the first
method to return a single instance.
Upvotes: 1