zernzern1993
zernzern1993

Reputation: 265

Filtering eloquent collection with array column

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. enter image description here

Upvotes: 0

Views: 617

Answers (1)

mdexp
mdexp

Reputation: 3567

Based on your comments, you are trying to have a role/permission system for your users.

Recommended solution

I kindly suggest you to use an external package like spatie/laravel-permissions or JosephSilber/bouncer that integrates nicely with laravel.

If you want to implement that anyways by yourself

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

Related Questions