Patrick Heppler
Patrick Heppler

Reputation: 181

Weird issue with Laravel relation in foreach loop

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

Upvotes: 0

Views: 360

Answers (3)

IndianCoding
IndianCoding

Reputation: 2683

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.

Upvotes: 2

Dilip Hirapara
Dilip Hirapara

Reputation: 15296

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');

Upvotes: 0

KiprasT
KiprasT

Reputation: 395

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.

Upvotes: 2

Related Questions