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

jamesaps's avatar

Limiting Permissions to Queries based on Roles

Say I have a model called 'Image' and also 'User'. Where users have roles which have certain permissions.

Now, each image belongs to a user.

But let's say a user requests example.com/images/

(All images basically)

And I want only images that the user has access to to display.

So admins can view any image, but users can only view images that belong to them or images that have a boolean 'public' set to true.

What is the best way to implement this?

Thanks

0 likes
2 replies
bart's avatar

You can simply add a permissions pivot table which stores the permission (user ID) to an image. In your images schema add an additional coulmn called is_public.

Finally, if a user hits route /images you simply has to fetch all public images + all images which the user has permission to (something like Images::ownedBy($userId)->get() or User::with('images')->get())

JarekTkaczyk's avatar

If User hasMany Images then you can go with:

// User model
use Illuminate\Database\Eloquent\Relations\Relation;
...
public function images()
{
   if ($this->isAdmin()) // place proper condition here depending on your implementation
   {
     return Relation::noConstraints(function () {
        return $this->hasMany('Image');
     });
   }

   return $this->hasMany('Image')->orWhere('public', 1);
}

For belongsToMany you can't do that (because it will return only the ones with entry in pivot table due to join), so you can do this in place:

if ($user->isAdmin) { $images = Image::all() }
else
{
  $images = Image::whereHas('users', function ($q) use ($user) {
    $q->where('users.id', $user->id);
  })->orWhere('public', 1)->get();
}

Please or to participate in this conversation.