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

Ligonsker's avatar

DB structure for individual file permissions

Hello,

I allow users to upload many files (images/videos mostly). By default only they can view these files. I want to allow them to "share" the files.

I was thinking to create a permission table which will store the user id that was given a permission to view a certain file and the file id.

But then it can end up having tens of thousands of rows in the table for each file - how bad is that for performance, and is there a better way to do it?

Ty

0 likes
3 replies
vincent15000's avatar

That should not be a problem, database queries are very fast. You just need to not forget to set indexes on the fields in the table.

The difference between with and without indexes can be very important, for example I already passed from 500 ms to 50 ms for the same query by just adding some indexes.

Indexes are precisely here to help the database to find quickly the indexed datas.

1 like
amerkrlicbegovic's avatar

A better approach would be to use a pivot table to store the many-to-many relationship between users and files. You can create a pivot table called file_user with columns file_id and user_id. This table would store a row for each user that has been granted permission to view a file.

Here's an example of how you could set up the pivot table and model relationships in your Laravel application:

// File model
class File extends Model
{
    public function users()
    {
        return $this->belongsToMany(User::class, 'file_user');
    }
}

// User model
class User extends Authenticatable
{
    public function files()
    {
        return $this->belongsToMany(File::class, 'file_user');
    }
}

With this setup, you can easily query the pivot table to determine which users have permission to view a given file. For example, to get all users that have permission to view a file with ID 1:

$file = File::find(1);
$users = $file->users;

Alternatively, you can also query the pivot table directly:

$users = User::whereHas('files', function($query) {
    $query->where('file_id', 1);
})->get();
1 like

Please or to participate in this conversation.