memele
4 months ago

How to use contains() on this collection?

Posted 4 months ago by memele

I am using a package to retrieve online users - https://github.com/thomastkim/laravel-online-users I have a global collection in AppServiceProvider that fetches all currently online users. Unfortunately this package doesn't provide a method for checking if a specific user is online and I am having trouble implementing this. I tried running contains() on the collection but it doesn't work. When I echo this collection with blade I get this:

[{"id":0,"user_id":2,"ip_address":"127.0.0.1","user_agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:66.0) Gecko/20100101 Firefox/66.0","payload":"YTo0O...,"user":{"id":2,"type":"user","name":"testuser","image":"default.png","email":"[email protected]","email_verified_at":null,"banned":0,"strikes":0,"created_at":"2019-05-09 10:21:58","updated_at":"2019-05-09 10:21:58"}}]

and in user view:

@if ($onlineUsers->contains($comment->user->name))
                <img src="/storage/img/avatars/{{$comment->user->image}}" alt="" height="50px" width="50px" style="border-radius: 100%; object-fit:cover; border: 4px solid lime">
            @else
                <img src="/storage/img/avatars/{{$comment->user->image}}" alt="" height="50px" width="50px" style="border-radius: 100%; object-fit:cover;">
            @endif

but it returns everything as true (all users get the green border, online or not)

if I change the condition to @if ($onlineUsers->contains('name', $comment->user->name)) then everything returns as false and online users don't get the green border.

and if I do @if ($onlineUsers->user->contains('name', $comment->user->name)) I get an error : Property [user] does not exist on this collection instance.

Please sign in or create an account to participate in this conversation.