This should get the reviews you want:
$reviews = Review::whereHas('service', function ($query) {
return $query->where('user_id', auth()->id());
})->orWhere('user_id', auth()->id())
->get();
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Hi everyone,
I'm new to Laravel and now am trying to work with Eloquent queries. However, I'm having trouble understanding how to compare a value in related table.
The application i'm trying to build contains three tables for now: Users, Services, and Reviews. The schema's look as following: User(id, name), Services(id, name, user_id, price), Reviews(id, content, user_id, service_id)
User Model
public function service()
{
return $this->hasOne('App\Service');
}
public function reviews()
{
return $this->hasMany('App\Review');
}
Service Model
public function reviews()
{
return $this->hasMany('App\Review');
}
Review Model
public function user()
{
return $this->belongsTo('App\User');
}
public function service()
{
return $this->belongsTo('App\Service');
}
Now I would like to get all the Reviews where the user_id = authenticated user or where the related Services have a user_id = authenticated user.
I tried something like this...
$user_id = Auth::user()->id;
$reviews = App\Review::where('user_id', $user_id)->orWhere.........->get();
However, after the 'orWhere' i'm clueless how to set the needed condition.
Hope there is someone out there that may have a solution or can explain to me what i'm doing wrong. Many thanks in advance.
You need to pass any variables from the outer scope into the Closure:
$reviews = Review::whereHas('service', function ($query) use ($userId) {
return $query->where('user_id', $userId);
})->orWhere('user_id', $userId)
->get();
Please or to participate in this conversation.