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

calin.ionut's avatar

view list of users that shared files with me (auth user)

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 ...

0 likes
7 replies
tykus's avatar

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());
});
calin.ionut's avatar

@tykus I have the relation in File model called sharedUsers .... but it gives me

Unknown column 'pivot' ...
tykus's avatar

@calin.ionut yeah...

User::whereHas('files.sharedWith', function (Builder $builder) {
	$builder->where('id', auth()->id());
});
calin.ionut's avatar

@tykus ... it works .... is more readable then mine :)

But how to get also the number of files that users has shared with me ?

tykus's avatar
tykus
Best Answer
Level 104

@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()
calin.ionut's avatar

I think i get it....

$users = User::whereHas('files', function($query) {
	$query->whereHas('sharedUsers', function($query) {
		$query->where('user_id', auth()->user()->id);
	});
})->get();

but need also the number of files....

Please or to participate in this conversation.