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

vincent15000's avatar

Query to test if a row exists ?

Hello,

I have a many-to-many relationship between two tables.

public function users()
{
    return $this->belongsToMany('App\Models\User', 'users_games')
        ->withPivot('score')
        ->withTimestamps();
}

I want to test if a user is registered in a game.

So I added this method.

public function isCurrentUserRegistered()
{
    $count = $this->withCount(['users' => function (Builder $query)
    {
        $query->where('user_id', Auth::check() ? Auth::user()->id : null);
    }])->get()->first()->users_count;
    return $count === 1;
}

The variable $count contains the right values : 0 or 1.

But the test $count === 1 always returns true.

What's the problem with my code ? I don't understand.

Someone has any idea ?

Thanks a lot ;).

Vincent

0 likes
6 replies
Sinnbeck's avatar

Try casting it

return (int) $count === 1;
vincent15000's avatar

Thanks for your answer @sinnbeck I already tried the casting, unfortunately this is not the solution.

bugsysha's avatar
Model::query()->has('users', fn ($q) => $q->where('user_id', $userId))->get();
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

Or you can try

$id = Auth::check() ? Auth::user()->id : 0;
return $this->users()->where('user_id', $id)->exists();
vincent15000's avatar

Thank you @sinnbeck that's the good code ! It wasn't soo difficult, but I didn't thought about it ;).

Please or to participate in this conversation.