Search code examples
phpormeloquentbelongs-tolaravel-5

Laravel 5.2: How to access data from belongsTo()?


I'm having some troubles with laravel 5.2 project which is, by the way, the first one with this framework, so I'm kinda newbie.

The thing is I've specified the relationship between these two tables 'supplier' and 'manager' so the manager can manage one to many supplier and a supplier is managed by one manager.

The models:

Class manager

public function suppliers(){
    return $this->hasMany('App\Supplier','id');
}

///////

Class supplier

public function manager(){
    return $this->belongsTo('App\Manager','id');
}

Ok. So now, from what I've read so far, accessing in a blade template the manager data embedded in a supplier should be as easy as this:

$supplier->manager->name 

But what I'm really getting back is an error which says

Trying to get property of non-object

What am I missing here?


Solution

  • Ok. Now I'm feeling stupid.

    All it takes it's to define correctly the foreing key which, of course, I was doing wrong. I've checked closely my foreing key definition in the supplier table and I realized that there wasn't an 'id' field. Instead I have a field named 'manager_id', so all it takes is to change this:

    public function manager(){
    return $this->belongsTo('App\Manager','id');
    }
    

    to this:

    public function manager(){
    return $this->belongsTo('App\Manager','manager_id');
    }
    

    And that's it. I can finally access to all the embedded data of the manager through the supplier. Sorry for my silly mistake. Thank you all.