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

cevizmx's avatar
Level 17

Breaking down Eloquent query

Hello there,

The following query works great.

$query = \DB::table('users')->join('posts', 'users.id','=','posts.user_id')->select('post_id','title')->get();

But I want to add a condition like;

$query = \DB::table('users')->join('posts', 'users.id','=','posts.user_id');
if($filter){
$query->where('title','like','%title%');
}
$query->get();

I know there is much better way like scopes but I am just curious if we wanted to do something like this, how we would solve it.

Thank you!

0 likes
4 replies
cevizmx's avatar
Level 17

Well sorted it out. Don't know why the reason but doing it like this works;

$result = $query->get();
return $result;

where directly returning the $query->get(); fails.

Snapey's avatar

In the first sample you posted, you were not returning the result of the query?

cevizmx's avatar
cevizmx
OP
Best Answer
Level 17

@Snapey,

I tried like

$query = \DB::table('users')->join('posts', 'users.id','=','posts.user_id');
if($filter){
$query->where('title','like','%title%');
}
return $query->get();

But it did not work. Then I assigned it to a variable and returned that variable worked.

$query = \DB::table('users')->join('posts', 'users.id','=','posts.user_id');
if($filter){
$query->where('title','like','%title%');
}
$result = $query->get();

return $result;

Again, its a very dumb example but just wondered how it would work :)

Snapey's avatar

Your first example here should behave no different to the second. There should be no need to fetch the data to a variable first.

But in the code you posted first, there was the return statement missing

Please or to participate in this conversation.