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

Reysa's avatar
Level 1

Laravel eloquent where data json array has user role

Hello

I hope my title doesn't confused you :D

I have a table called "Notifications" which I add my custom notifications in it for specific roles

this is the "Messages" tabel strcuture

id | roles | message
1    | ["superadmin","trial"] | test message

now I want to only users who has "superadmin" role or "trial" role can see this message.

this is my "User" table strcuture

id | roles | name
1   | ["superadmin"] | reysa
2  | ["admin","moderator"] | user
3 | ["trial"] | user 2

how can I do this in eloquent with a where() function? is it possible or I have to go get all the data and then filter them one by one with foreach based on user roles.

I have many roles (almost 11) that's why I want to filter the data with where() while I'm calling the eloquent

thanks in advanced

0 likes
8 replies
Reysa's avatar
Level 1

@MohamedTammam no no you both got it wrong I think :D

I don't want to get "Users" where they have "superadmin" , I want to get data from first time (Messages) where user has a role that message has

based on the example tables , both user id 1 and 3 should be able to see the message id 1 because they have "superadmin" and "trial" in their roles

I've already tried wherJsonContains but it returns null , because both $message->roles and $user->roles are json array

another thing is my user might have a role that it's not in messages->roles

Reysa's avatar
Level 1

@MohamedTammam still return null

because my user roles is like this:

["superadmin","admin","booster","moderator"]

but the message roles is this

["superadmin"]

so it's not equal and returns null

but what I want is , if my user has the one of the roles in message table , I get that data

MohamedTammam's avatar
Level 51

@Reysa Try

$query = Message::query()
foreach(json_decode($user->roles) as $role)
	$query->orWhereJsonContains('roles', $role)

$messages = $query->get();
1 like
Reysa's avatar
Level 1

@MohamedTammam that works perfectly!! thanks man <3

I did that before but the problem was I used whereJsonContians instead of ORwhereJsonContains sometimes I hate my job :D

Please or to participate in this conversation.