Home > Software engineering >  Eloquent relationship returns nothing
Eloquent relationship returns nothing

Time:07-26

I am trying to make a system that allow users to create playlists which add on it movies there favorites movies or songs.

I named the main model "Top". I also have models : User, Category, Liste_top (this name is bad but it make de junctions beetween a Top and a Movie/Song. A better name, I guess, would be something like "top_media".

So on my view I can retrieve the User datas and the Categories datas, but the Liste_top returns an empty collection, I do no understand why.

Here is my Lise_top Model :

class Liste_top extends Model
{
     use HasFactory, Notifiable;

     protected $fillable = [
       
      'top_id',
      'medias_id'
  ];
 
      public function tops()
    {
        return $this->belongsToMany(Top::class);
    }
    
    public function medias()

  {
        return $this->hasMany(Medias::class);
    }

The request on my TopController.php :

$tops = Top::with(
                    'user:id,name,email',
                    'liste_tops:id,medias_id',
                    'categories:title,slug'
                )->paginate(20); 

And the function on my Top Model :

public function liste_tops()
{
    return $this->hasMany(Liste_top::class);
}

A dd() returns this :

#relations: array:3 [▼
          "user" => App\Models\User {#1703 ▶}
          "liste_tops" => Illuminate\Database\Eloquent\Collection {#1698 ▼
            #items: []
            #escapeWhenCastingToString: false
          }
          "categories" => Illuminate\Database\Eloquent\Collection {#1699 ▶}

As you can see, I retrieve the User datas, the categories datas, but none from the List_top, that are just a intermediate table that relies a top from all the medias the user liked.

I would like to retrieve the datas from the medias table to do something like on my view :

{{ $top->liste_top->media->title }}

CodePudding user response:

You need to also include the related key in the query i.e. top_id:

$tops = Top::with(
    'user:id,name,email',
    'liste_tops:id,top_id,medias_id',
    'categories:title,slug'
)->paginate(20);

Without this, Eloquent has not way of mapping the relationship.

  • Related