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

lara230832's avatar

Eloquent - 'where' in belongstoMany relationship

Newbie question here :-)

Is this the proper way to 'where' in belongstoMany relationship?

 $platforms = Platform::with('users')
            ->whereHas('users', function ($q) {
                $q->where('id', '=', Auth()->user()->id);
            })
            ->orderBy('id', 'desc')
            ->get();

Looks like I'm not using proper Eloquent for this...

0 likes
4 replies
lara230832's avatar

@Nakov Thanks! It is working as it should. But I thought there must be a nicer/cleaner way :-)

MichalOravec's avatar
Level 75

You code could look like this

$platforms = Platform::with('users')
    ->whereRelation('users', 'id',  auth()->id())
    ->orderByDesc('id')
    ->get();
1 like

Please or to participate in this conversation.