Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 437
Robert Lee Avatar asked Oct 21 '22 00:10

Robert Lee


2 Answers

Try:

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

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

like image 95
anhlc Avatar answered Oct 22 '22 15:10

anhlc


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();
like image 35
Yako Avatar answered Oct 22 '22 16:10

Yako