how to create a parent and sub category in laravel 8 code example
Example: laravel parent child category
Calling the relationship function (->children()) will return an instance of the relation class. You either need to call then get() or just use the property:
$children = $category->children()->get();
$children = $category->children;
Further explanation
Actually children() and children are something pretty different. children() just calls the method you defined for your relationship. The method returns an object of HasMany. You can use this to apply further query methods. For example:
$category->children()->orderBy('firstname')->get();
Now accessing the property children works differently. You never defined it, so Laravel does some magic in the background.
Let's have a look at Illuminate\Database\Eloquent\Model:
public function __get($key)
{
return $this->getAttribute($key);
}
The __get function is called when you try to access a property on a PHP object that doesn't actually exist.
public function getAttribute($key)
{
$inAttributes = array_key_exists($key, $this->attributes);
if ($inAttributes || $this->hasGetMutator($key))
{
return $this->getAttributeValue($key);
}
if (array_key_exists($key, $this->relations))
{
return $this->relations[$key];
}
$camelKey = camel_case($key);
if (method_exists($this, $camelKey))
{
return $this->getRelationshipFromMethod($key, $camelKey);
}
}
Then in getAttribute first is some code that checks for "normal" attributes and returns then. And finally, at the end of the method, if there's a relation method defined getRelationshipFromMethod is called.
It will then retrieve the result of the relationship and return that.