Laravel belongsTo only returns the id and not the entire object
Asked Answered
S

3

7

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

Slate answered 15/10, 2014 at 23:52 Comment(1)
There is something wrong with your relationships. Try to make sure you are referencing the right local_key and parent_key .. $this->belongsTo('Album', 'local_key', 'parent_key');Erl
V
2

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();
Verona answered 9/4, 2015 at 8:0 Comment(0)
R
2

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');
}
Remnant answered 2/11, 2020 at 11:40 Comment(1)
way more best practicesInhesion
R
1

Try:

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

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

Reseta answered 16/10, 2014 at 5:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.