Reputation: 265
I am trying to filter eloquent model by a column with is an array. I want to the whole model where that particular column contains a certain element in it (in the array).
I have tried using this :-
$admins = User::where('role', ['admin'])->paginate(15);
The role is the column which is an array and I want to filter the whole collection where that array column contains the string element of 'admin' but this returns an empty collection.
Upvotes: 0
Views: 617
Reputation: 3567
Based on your comments, you are trying to have a role/permission system for your users.
I kindly suggest you to use an external package like spatie/laravel-permissions or JosephSilber/bouncer that integrates nicely with laravel.
However, Laravel (or I would better say MySQL/PostgreSQL) support json field type, that might achieve something like what you are looking for. The part I'm not sure about is to look for a value inside the array.
You can see all the available JSON field wheres in the documentation here.
Anyways, if you want to implement that yourself without the limited JSON support I would restructure the database to have these tables:
users (all the fields you have, except for role and permissions)
user_role (id, user_id, role_id)
roles (id, name, display_name)
user_permission (id, user_id, permission_id)
permissions (id, name, display_name)
With that database you just have to set up the correct relationships for the User, Role and Permission models.
That last method is the way these packages more or less handles their stuff (roles/permissions) internally, and it's definitly a better approach to JSON columns in your users table.
Upvotes: 1