1

I am trying to return data from my database and I want it to include data from the related table. It is a one-to-many relationship. However I all I get is an error

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

In my User model I have

//App\User.php
class User extends Authenticatable{
    use Notifiable;

    public function systems(){
        return $this->hasMany(\App\Models\General\systems::class,'added_by','id');
   }

The other model, called systems I have

//App\Models\General\systems.php
class systems extends Model
{
    public function User(){
        return $this->belongsTo(\App\User::class,'added_by','id');
}

In my controller I have

$this->systemsObject = new \App\Model\General\systems();

$systems = $this->systemsObject->get()->User;

according to the Laravel Documentation this should work but it isn't. I tried reversing the foreign key/local key parameters. I made the ->User uppercase, lowercase.

I have no idea what I am doing wrong

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
JoeyD473
  • 2,890
  • 2
  • 21
  • 25

1 Answers1

1

You need to iterate over the collection, for example:

$systems = $this->systemsObject->get();
foreach ($systems as $system) {
    echo $system->User->name;
}
Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279