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
@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
You should only use
%
symbol at the end of yourwhere
clause value (eg:admin_side_barmenu%
) so that theDB
knows you only want the rows starting withadmin_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.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.