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

Scotalia's avatar

Getting Error when trying to return users from DB

It's been 3+ hours and I can not for the life of me pull users from my Users table using a DB:: query.

My goal is to display the number of Users following all Competitions for a given Confederation. So basically all Users under a specific Confederation.

My function is here:

public function users() {

    // grab all competitions under this confederation
    $compIDs = $this->comps()->select('id')->where('confederation_id', '=', $this->id)->get();
    // loop through all competitions and grab the user IDs from the users_competitions table
    $userIDs = DB::table('users_competitions')->select('user_id')->whereIn('competition_id', $compIDs)->get();
    //  grab all the users from the users table by their id
    $users = DB::table('users')->select('username')->whereIn('id', $userIDs)->get();
    
    return $users;
}

When i call it, i receive 1 of 2 'errors' (depending on the various 'fixes' I have tried): 1. an empty array for $users (there should be a SINGLE match currently); 2. 'object of class not be converted to string' error.

My database consists of the following tables:

Confederations (primary key: id) Competitions (primary key: id, foreign key to Confederations: confederation_id) Users (primary key: id) Users_Competitions (pivot/relationship table) (foreign keys to Competitions / competition_id and Users / user_id)

I have the following models:

Confederations Competitions Users (no model for the pivot table)

I was originally hoping i could perform a hasManyThrough relationship from the Confederations Table -> Competitions -> Users_Competitions -> Users, but i was unsuccessful in finding a way to do this.

This seems like it should be VERY simple but i can't for the life of me figure out what i need to do nor what i am doing wrong. I am very frustrated.

0 likes
4 replies
Vilfago's avatar
Vilfago
Best Answer
Level 20

As you have a relational database, use join.

$users =  DB::table('users')
    ->join('users_competitions', 'users.id', '=', 'users_competitions.user_id')
    ->join('competitions', users_competitions.competition_id', '=', 'competitions.id')
    ->where('competitions.confederation_id', $this->id)
    ->select('users.username')
    ->get()

Or probably could be cleaner with Eloquent relations and whereHas.

Cronix's avatar

@Scotalia Please mark as solved by clicking the checkbox under the users avatar next to the post that helped

Scotalia's avatar

sorry meant to mark as best answer and walked away from from computer, never to return...all set now. thanks again! @Vilfago

Please or to participate in this conversation.