skip to Main Content

I am working in larael9 with spatie package to manage roles and permissions.
I want to fetch user permissions with where condtion.

my permissions table is as following

id | name                           | guard_name    | created_at          | updated_at
-------------------------------------------------------------------------------------------------
14 | admin_side_barmenu_dashboard   | web           | 2022-09-29 13:52:00 | 2022-09-29 13:52:00
    
15 | admin_side_barmenu_users       | web           | 2022-09-29 13:52:00 | 2022-09-29 13:52:00
    
16 | admin_side_barmenu_settings    | web           | 2022-09-29 13:52:00 | 2022-09-29 13:52:00
    
17 | admin_side_barmenu_roles       | web           | 2022-09-29 13:52:00 | 2022-09-29 13:52:00
    
18 | admin_side_barmenu_permission  | web           | 2022-09-29 13:52:00 | 2022-09-29 13:52:00

what i am trying to achieve is, get permissions were name start with 'admin_side_barmenu' for auth user
I am able to get all the permissions but not able to get where it start with 'admin_side_barmenu'.

I have tried the following way.

auth()->user()->getAllPermissions()->where('name', 'like', '%admin_side_barmenu%')->toArray();

Following is working for me if it fetchs with full name

auth()->user()->getAllPermissions()->where('name', 'like', 'admin_side_barmenu_dashboard')->toArray();

Thanks!

2

Answers


  1. Chosen as BEST ANSWER

    @ths

    Thank you so much for your time.

    I have made some changes in your answer. and its working for me. Thanks for the help

    auth()->user()
        ->getAllPermissions()
        ->filter(fn($p) => Str::startsWith($p->name, 'admin_side_barmenu',))
        ->toArray());
    

  2. You should only use % symbol at the end of your where clause value (eg: admin_side_barmenu%) so that the DB knows you only want the rows starting with admin_side_barmenu and can have 0 or more characters from the right.

    UPDATE

    After checking the package, it seems getAllPermissions return a collection and doesn’t make a direct DB call, So we need to filter the return collection from that method.

    use IlluminateSupportStr;
    
    auth()->user()
      ->getAllPermissions()
      ->filter(fn($p) => Str::startsWith($p, 'admin_side_barmenu')) // only return permissions starting with "admin_side_barmenu"
      ->toArray();
    

    Based on the data sample found in your question, the above query should return all the rows from the table because they all start with admin_side_barmenu substring.

    Learn more about Pattern Matching on MySQL docs.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search