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

Ligonsker's avatar

Many to many relationship: retrieving all items from Table1 with specific value from Table2

I have a many to many relationship: folder_file which lists folder_id and file_id. What is the proper way to get all the files with specific folder_id? In the following example, I want to retrieve files from folder with id 1, so files with id 1 and 2:

folder_id |  file_id
----------|----------
     1    |     1
     1    |     2
     2    |     3
     3    |     4

I have the models File and Folder (with corresponding tables files and folders), and relationships set up correctly

0 likes
9 replies
vincent15000's avatar

You can use the relationship defined in the Folder model.

public function files()
{
	return $this->belongsToMany(App\Models\File::class);
}
...
$folder = Folder::find($folder_id);
$files = $folder->files;
1 like
Ligonsker's avatar

@vincent15000 Oh I have to get the folder first. I thought I could do something similar to this (Though couldn't find the right syntax):

$files = Auth::user()->with('files')->where('folder_id', '=', 1)->get();

or

$files = Auth::user()->files()->wherePivot('folder_id', '=', 1)->get();

though I get certain errors, for example Unknown column 'pivot' in 'where clause' because I guess it completely wrong

Is there something in this style?

1 like
vincent15000's avatar

@Ligonsker

$files = Auth::user()->with(['files' => function ($query) {
	$query->where('folder_id', 1);
})->get();

If you need to have the folder id value dynamically, you need to declare it to be used in the closure.

$folder_id = 1;
$files = Auth::user()->with(['files' => function ($query) use ($folder_id) {
	$query->where('folder_id', $folder_id);
})->get();
1 like
Ligonsker's avatar

@vincent15000

It is not working in this case because it looks for the folder_id in the files table, not the folder_file pivot table and I get the same error I was getting before, that folder_id column is not found

1 like
frankielee's avatar

Assuming the relationship is User hasMany file Example:

auth()->user()->load(['files.folder'=>fn($query)=>
		$query->where('folder_id',1)->whereIn('file_id',[1,2]);
]);

1 like

Please or to participate in this conversation.