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

aivis's avatar
Level 14

User roles and permissions with conditions

I want to implement roles & permissions and have some sort of conditions for the permissions. What I mean by conditions is, for example:

  • There are two roles: user and superuser
  • There is a permission: add-post
  • user can only add 5 posts
  • superuser can add unlimited number of posts

I looked for some packages I could use, for example:

All of them have nice examples, but I couldn't find any information about the "condition" part I would like to have.

I guess the simplest solution would be to use one of the packages and just hard-code the condition:

if ( ! $user->can('add-post')) {
    // throw exception or whatever
}

if ( ! $user->hasRole('superuser') && $postCount > 5) {
    //
}

But I don'y really like that...

This kind of API would be cool to use:

if ( ! $user->can('add-post', ['count' => $postCount])) {
    //
}

Is there some package with this kind of functionality? Couldn't find any, maybe I didn't use the right keywords when searching... If not, I guess I would need to extend some existing package/create this from scratch.

Have you implemented this kind of functionality in your projects/how would you implement this?

Thanks!

0 likes
3 replies
jekinney's avatar

Imo your over thinking it. Are you trying to set the max post count dynamically? Ie: Change it any time. If not the && check with post count is pretty simple and effective.

aivis's avatar
Level 14

Yes that was the idea, so that I could easily change the conditions without changing the code.

But I guess you are right, I might be over thinking this. I could start with the simple if statements and if I really need to change it often I could improve it.

I just thought this is a somewhat common functionality and there could be packages for this, but couldn't find any.

jekinney's avatar

I have, but is hugely problematic (getting it right in code and mentally lol) used a polymorphic many to many that a super user could dynamically set permissions per page and areas of the page.

For your case you could set up a settings table that you could set the maximum posts. Query the settings table to get permission name and post count for your check.

Please or to participate in this conversation.