Robert Lee
Robert Lee

Reputation: 105

Laravel belongsTo only returns the id and not the entire object

I was under the impression that when I use a belongsTo relationship in my model, it will return the object but I seem to only get the id. Is this supposed to happen and what is the benefit of this?

This is my code:

From my Photo model

public function album()
{
    return $this->belongsTo('Album', 'album');
}

And my PhotosController

$photo = Photo::find($id);
$album = $photo->album;
return 'albums/' . $album->folder . '/thumbs/' . $photo->file;

Don't mind the return, it's just for testing. I get an error:

Trying to get property of non-object

And a var_dump() shows that all I get is a string with the album's id

Upvotes: 7

Views: 3197

Answers (3)

Davide Casiraghi
Davide Casiraghi

Reputation: 18117

You get the id because your foreign key field has the same name as your relation.

So when you call $photo->album you are not touching the relation method (as dynamic property), but returning album field value, which happens to be the id.

The best is to rename the album field to album_id.

public function album()
{
    return $this->belongsTo('Album', 'album_id');
}

Or since it follows the standard naming you can avoid specifying the album_id

public function album()
{
    return $this->belongsTo('App\Album');
}

Upvotes: 2

Yako
Yako

Reputation: 3484

I had the same problem. I'm still not able to explain what happens. If you dump photo, I guess you would get both the album's id, and the album object in the relationships.

Threrefore, I somehow got it like this:

$album = $photo->album()->first();

Upvotes: 2

anhlc
anhlc

Reputation: 14469

Try:

return $this->belongsTo('Album', 'album', 'id');

where 'id' is the name of the associated column on the album table

Upvotes: 1

Related Questions