Search code examples
phplaraveleloquentlaravel-5.5

Why I can't retrieve data using a one-to-many relationship in laravel 5.5


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


Solution

  • You need to iterate over the collection, for example:

    $systems = $this->systemsObject->get();
    foreach ($systems as $system) {
        echo $system->User->name;
    }