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

mtm81's avatar
Level 1

Easy to fix Pivot Eloquent query

Hi, Newbie at laravel so have a pretty basic question I'm looking for a pointer on if possible. I have a simple manytomany DB setup. Users Docs DoctoUserLinks (this is the table linking the two up).

So one user can be linked to many documents One document can be linked to many users Critically, a document can also NOT be linked to any user, in which case it's a 'community doc' available for any user to use.

All straight forward so far.

So, I created a couple of functions to handle the link up. For seeing all docs linked to a doc in the User Model, I've got

public function userdocs() { return $this->belongsToMany('App\Doc', 'docto_user_links','userid', 'docid') }

Now, this is the bit I just can't get the right syntax for - as well as the doc-user relationship working in the above statement, I also need to return as part of the same query all the docs which aren't linked to anyone

So if lets say we have a user with an ID of 1 And lets say we have three docs, doc1, doc2 & doc3

If, in my pivot table I had a reference for userid being linked to doc1. Doc 2 was in that table as well, but not linked to user 1, critically, doc3 wasn't in the pivot table at all.

Therefore, in my query above, I would expect doc1 and doc3 to be returned.

What's the best of achieving this?

Many thanks for any replies!

0 likes
2 replies
Snapey's avatar
Snapey
Best Answer
Level 122

I don't think you can make the relationship responsive in this way, but you can turn it on its head a little and ask for docs that have specific user or no user

somethinglike

$docs = Doc::whereHas('users',function($query) use($user){
                        $query->where('userid',$user->userid);
                })
                ->orDoesntHave('users')
                ->get();

You could test these individually to check you get the user's docs, and then no user's docs

mtm81's avatar
Level 1

Excellent! - thanks for the reply and pointing me in the right direction. Got it all sorted .

Many thanks

Please or to participate in this conversation.