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

ileanap's avatar

foreach loop doesn't show any entities in object array (which isn't empty)

I have a three tables, Users, Events and Attends. Simply put, users which attend events are stored in the attends table. users and events have the id column, while Attends has id, user_id, and event_id. I want to pass to the profile of the user a list of the events s/he attends (as Event objects, as I want to get both the name and the id of an event). I created models for all three tables (User, Event, Attend) the code in the UserProfileController is as follows:

$userAttendsObjectArray = Attend::where('user_id',$userId);
        $userEventsIds = [];
        foreach($userAttendsObjectArray as $userAttendsObject){
            $userEventsIds[] = $userAttendsObject->event_id;
        }
        $userEvents = Event::where('id',$userEventsIds);
        return view('pages.profile', compact('user','userEvents'));

The profile.blade.php part of the code is: if(count($userEvents) != 0)

@else

He didn't attend any event

@endif

The message "He didn't attend any event" doesn't show up, yet no event names are shown either. I don't understand.

The attends table have one line with user 59 attending event 16 (both the users with id 59 and the event with the id 16 exist in the database)

0 likes
4 replies
EventFellows's avatar
Level 16

If I get your code right your issue is here because $userEventsIds is an Array (and $userEvents will be an empty collection):

$userEvents = Event::where('id',$userEventsIds);

So try to use the ->whereIn() instead of ->where() and it shoud work.

Here are the details: https://laravel.com/docs/5.4/queries#where-clauses

1 like
ileanap's avatar

thank you guys. I'll look into it :D

ileanap's avatar

after centuries of fighting, I finally found the winning formula ^_^ (I also forget to add ->get(), silly me >_<)

Please or to participate in this conversation.