laravel parent child category

Solutions on MaxInterview for laravel parent child category by the best coders in the world

showing results for - "laravel parent child category"
Ronnie
16 Oct 2017
1Calling the relationship function (->children()) will return an instance of the relation class. You either need to call then get() or just use the property:
2
3$children = $category->children()->get();
4// or
5$children = $category->children;
6Further explanation
7Actually 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:
8
9$category->children()->orderBy('firstname')->get();
10Now accessing the property children works differently. You never defined it, so Laravel does some magic in the background.
11
12Let's have a look at Illuminate\Database\Eloquent\Model:
13
14public function __get($key)
15{
16    return $this->getAttribute($key);
17}
18The __get function is called when you try to access a property on a PHP object that doesn't actually exist.
19
20public function getAttribute($key)
21{
22    $inAttributes = array_key_exists($key, $this->attributes);
23
24    // If the key references an attribute, we can just go ahead and return the
25    // plain attribute value from the model. This allows every attribute to
26    // be dynamically accessed through the _get method without accessors.
27    if ($inAttributes || $this->hasGetMutator($key))
28    {
29        return $this->getAttributeValue($key);
30    }
31
32    // If the key already exists in the relationships array, it just means the
33    // relationship has already been loaded, so we'll just return it out of
34    // here because there is no need to query within the relations twice.
35    if (array_key_exists($key, $this->relations))
36    {
37        return $this->relations[$key];
38    }
39
40    // If the "attribute" exists as a method on the model, we will just assume
41    // it is a relationship and will load and return results from the query
42    // and hydrate the relationship's value on the "relationships" array.
43    $camelKey = camel_case($key);
44
45    if (method_exists($this, $camelKey))
46    {
47        return $this->getRelationshipFromMethod($key, $camelKey);
48    }
49}
50Then 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.
51
52It will then retrieve the result of the relationship and return that.