Reputation: 496
I wan't to get the id
of sub-category
that is under category
. I tried passing the value of id
in the route file using
$categories->subcategory->id
However it gives me an error of:
Property [subcategory] does not exist on this collection instance.
Here's my relationship:
Category
class Category extends Model
{
protected $fillable = ([
'name'
]);
public function subcategory(Type $var = null)
{
# code...
return $this->hasMany(Subcategory::class,'category_id','id');
}
}
And here's my blade
<form action="{{route('subcategory.update', $categories->subcategory->id)}}">
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</form>
Controller
public function create()
{
$categories = Category::all();
// dd($categories);
return view('settings.create', compact('categories'));
}
Upvotes: 2
Views: 66
Reputation: 561
It sounds like your $categories
variable is a collection of Category::class
?
Keep in mind that the subcategory
function will return multiple items, because of the HasMany
$categories->first()->subcategory->first()->id
OR
$categories->subcategory->first()->id
If not, you could add the subcategory
relationship to the Category::class
to the $with
array, so it's automatically loaded in. And try again.
$with
array:class Category extends Model
{
protected $with = ['subcategory'];
}
Upvotes: 3