Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

binggle's avatar

BelongsToMany take 1 .

hi . I have two models and pivot table..

See the relations.

Cat.php

class Cat extends Model
{

    public function videos()
    {
        return $this->belongsToMany( Video::class, 'cat_video' )->withTimestamps();
    }
    
    function videoOne()
    {
        return $this->videos()->orderBy('created_at', 'desc')->take(1);
    }

}

Video.php


class Video extends Model
{
    public function cats()
    {
        return $this->belongsToMany(Cat::class, 'cat_video');
    }

}

I want to get the latest video at each category ( cat. ) .

$cats = Cat::with('videos')->get();

It returns videos ..

$cats = Cat::with('videoOne')->get();

It returns nothing ..

how can I get it ?

0 likes
6 replies
binggle's avatar

I see the ref.


$category = Cat::find(1);

foreach ($category->videos as $video) {
    //
}

But if i use this code in Controller, not Model I can not use 'Eager Loading' and 'Cache' for 'video' model ..

I wish I can adopt this code on Model.

Neeraj1005's avatar

@binggle your relationship is wrong...make proper relationship...as @tisuchi said.

  • cat Model hasMany videos
  • videos Model belongsToMany cats
binggle's avatar

Is it possible to build relationship with 'hasMany' / 'belongsToManay' pair ?

I don't get it.

Please or to participate in this conversation.