php – Eloquent accessing related data in Laravel

I’m trying to get relations from data returned.

in User

public function folders()
{
  return $this->hasMany("AppFolder");
}

public function rootFolder()
{
  return $this->folders()->where("parentid", null);
}

in Folder

public function subFolders() {
  return $this->hasMany("AppFolder", "parentid");
}

public function parentFolder()
{
  return $this->belongsTo("AppFolder", "parentid");
}

in Controller

$root = auth()->user()->rootFolder;
$subs = $root->subFolders;
foreach ($subs as $sub) {
    echo $sub->name;
}

I’m getting

Property [subFolders] does not exist on this collection instance.

However if

$root = new Folder;

Exception disappears.

Do I have to somehow tell the return data from rootFolder function that you are a Folder?

Leave a Reply