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.
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
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!
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 :)
Please or to participate in this conversation.