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
membertomember_id,covertocover_idon yourgalleriestable, you do not need to explicitly setforeign keyandlocal key, and you problem is solved, imo.setEagerLoads?