Giedrius
Giedrius

Reputation: 1390

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!

Upvotes: 4

Views: 1210

Answers (1)

Paul Spiegel
Paul Spiegel

Reputation: 31832

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.

The priority/order of what is to be returned is:

  • Public object property (public $main_page)
  • GetAccessor ($page->getMainPage())
  • Table column/attribute ($page->attributes['main_page'])
  • Attribute/column from table ($this->attributes['main_page'])
  • Loaded relation ($this->relations['main_page'])
  • Unloaded relation ($this->main_page()->get())

Upvotes: 2

Related Questions