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

Quiet_Molly's avatar

Array to string conversion error on Laravel 9

I`m using Spatie to easily manage roles in my application. I decided to use it also for custom validation(since it's also using middleware for it)

I would like to display users which doesnt have role activated

To achieve this: I'm getting all users

$users = User::get();

and all Users with activated role

$activatedUsers = User::role('activated')->get();

untill this moment, everything goes smooth, arrays got the same structure, displaying different count of users(as intended) but when I'm trying to compare them using array_diff

$notActivatedUsers = array_diff($users, $activatedUsers);

Error:
'Array to string conversion' 

excacly on line 27 which is array_diff. I dont have any idea why it outputs this error

0 likes
2 replies
tykus's avatar
tykus
Best Answer
Level 104

You are working with Collections here; just use the Collection diff method instead of array_diff:

$notActivatedUsers = $users->diff($activatedUsers);

However, it would be more performant to make just one query (basically the opposite of User::role('activated')->get() however that is implemented, e.g.

$notActivatedUsers  = User::hasntRole('activated')->get()
1 like

Please or to participate in this conversation.