Giedrius Giedrius - 3 months ago 29
PHP Question

Laravel Eloquent belongsTo not working

I can't make the

belongsTo
relationship work (or I am using wrong relationship).

My database structure (simplified):

pages:


id | title | main_image
-----------------------
1 | Test | 5


media:


id | filepath
-----------------------
5 | uploads/test.jpg


So I want to be able to do
$page->main_image
and it would return me instance of the Media model, so I could use
$page->main_image->filepath
etc.

In the
Page
model I have the following:

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


But when I do
$page->main_image
I just get
int 5
. Am I using the wrong relationship here?

Thanks!

Answer

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.

Comments