Giedrius Giedrius - 1 year ago 129
PHP Question

Laravel Eloquent belongsTo not working

I can't make the

relationship work (or I am using wrong relationship).

My database structure (simplified):


id | title | main_image
1 | Test | 5


id | filepath
5 | uploads/test.jpg

So I want to be able to do
and it would return me instance of the Media model, so I could use

In the
model I have the following:

public function main_image()
return $this->belongsTo('App\Modules\Media\Models\Media', 'id', 'main_image');

But when I do
I just get
int 5
. Am I using the wrong relationship here?


Answer Source

When accessing $page->main_image Eloquent will only try to find the main_image() relation if there is no attribute with the same name. But you already have a column name main_image. So you should either rename the attribut (column name) or the relation. I would rename the column to main_image_id.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download