0

I'm currently facing a weird issue with one of my Laravel Models.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Gallery extends Model
{
    protected $guarded = ['id'];
    protected $with = ['member','photos', 'cover'];

    public function member()
    {
        return $this->hasOne(Member::class, 'id', 'member')->setEagerLoads([]);
    }

    public function cover()
    {
        return $this->hasOne(Photo::class, 'id', 'cover')->setEagerLoads([]);
    }

    public function photos()
    {
        return $this->morphMany('App\Models\Photo', 'photoable')->setEagerLoads([]);
    }
}

If I dump all galleries, each gallery has a cover which is a Instance of App\Models\Photo

$galleries = Gallery::all();
dump($galleries);

This also works with $galleries->toJson() and $galleries->toArray()

However, if I loop over galleries, cover is only an integer.

$galleries = Gallery::all(); 
foreach($galleries as $gallery){
   dump($gallery->cover);  // Integer instead of App\Models\Photo
}

While this returns a App\Models\Member:

$galleries = Gallery::all(); 
foreach($galleries as $gallery){
   dump($gallery->member); //Instance of App\Models\Member
}

Laravel: 6.6.2 PHP: 7.4

2
  • You need to combine all answers here to solve this issue. If you change member to member_id, cover to cover_id on your galleries table, you do not need to explicitly set foreign key and local key, and you problem is solved, imo. Commented Dec 9, 2019 at 9:18
  • why are you calling setEagerLoads? Commented Dec 9, 2019 at 9:25

3 Answers 3

2

Your Gallery model attribute $cover has the same name as relation.

Your model use $cover attribute which have integer value (foreign key to related model).

You could rename column cover for example to cover_id.

Sign up to request clarification or add additional context in comments.

1 Comment

it will always return the attribute not the relationship, regardless of whether it is loaded or not ... getAttribute checks for the attribute before then looking for the relationship
2

Relationship name cannot be the same as the column name in the table. Rename one or the other, would recommend to rename the column to cover_id.

Comments

0

You passed the wrong place of param in a relationship.

pass it as below.

public function member()
{
    return $this->hasOne(Member::class, 'member','id')->setEagerLoads([]);
}

public function cover()
{
    return $this->hasOne(Photo::class,'cover','id')->setEagerLoads([]);
}

Here example of laravel doc.

return $this->hasOne('App\Phone', 'foreign_key', 'local_key');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.