If you have the reciprocal berlongsToMany relation on the File model named sharedWith, then this should work:
User::whereHas('files.sharedWith', function (Builder $builder) {
$builder->wherePivot('user_id', auth()->id());
});
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I am having 3 tables:
users, files and pivot table shared_files
I have also created the relations in model User:
public function files() {
return $this->hasMany(File::class);
}
public function sharedFiles() {
return $this->belongsToMany(File::class, 'shared_files')->withPivot('can_version');
}
The shared_files (file_id, user_id, can_version) - contains the users that have access to one or more files.
The question is how can I query the user (id, name, number_of_files) that he has shared with me ? (auth()->user()-id)
I need the list of users that have files that they shared with me ...
@calin.ionut sorry; meetings...
Anyway, I don't know that there is an easy way to achieve the count using relations like you need. You can get the same information using JOINs however, e.g.
User::query()
->selectRaw('users.*, count(shared_files.file_id) as files_shared')
->join('files', 'files.user_id', 'users.id')
->join('shared_files', 'shared_files.file_id', 'files.id')
->where('shared_files.user_id', auth()->id())
->groupBy('users.id')
->get()
Please or to participate in this conversation.