Get all parent categories

Posted 2 months ago by stefan7

Hi,

I have a category model with parent_id attribute. I am trying to write a function that gives me all the parents. dd($parent) returns only string: "parent_id" What am I missing? And what is here the difference between $parent = $this->parent(); and$parent = $this->parent; ??

    public function parent()
    {
        return $this->belongsTo('App\Models\Category', 'parent_id', 'id');
    }

    public function getAllParents()
    {
        $parents = collect([]);
        $parent = $this->parent;

        while(!is_null($parent)) {
            $parents->push($parent);
            $parent = $parent->parent;
        }

        return $parents;
    }

dd($this) returns object

Category {#399 ▼
  #parent: "parent_id"
  #appends: array:1 [▶]
  +fillable: array:3 [▶]
  #connection: "mysql"
  #table: null
  #primaryKey: "id"
  #keyType: "int"
  +incrementing: true
  #with: []
  #withCount: []
  #perPage: 15
  +exists: true
  +wasRecentlyCreated: false
  #attributes: array:7 [▼
    "id" => 7
    "parent_id" => 3
    "en_name" => "Category 7"
    "de_name" => "Kategorie 7"
    "slug" => "category7"
    "created_at" => "2019-06-03 11:27:37"
    "updated_at" => "2019-06-03 11:27:37"
  ]

I tried also this

$parent = $this->parent();

Which returns me, but is not accessible

BelongsTo {#419 ▼
  #child: Category {#399 ▶}
  #foreignKey: "parent_id"
  #ownerKey: "id"
  #relation: "parent"
  #query: Builder {#402 ▶}
  #parent: Category {#399 ▶}
  #related: Category {#418 ▶}
  #withDefault: null
}

Please sign in or create an account to participate in this conversation.