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

nutkani1337's avatar

Getting following error while fetching records from DB : Object of class stdClass could not be converted to string

Hey Folks, I'm gettng "Object of class stdClass could not be converted to string" while fetching records from DB.

Scenario

I have table called "TripData" where i have stored all the information of trip that user has planned (including userID,Trip Date, trip country , lat , long etc). Now I'm working on a feature where user can see nearby people. For that I'm allowing a user to select his planed city and see nearby user.

Now coming to the problem:

I want to pass the country name to DB Query to get all the user with same country. For that i have written following query:

// This is working fine returning the country name that i have seleced

$trip_country = DB::table('trip_data')->where('id',$request->people_near_by)->get(['trip_country']);

// Based on above country i want to fetch all the user having same country for that i have written the below query

$all_trip = DB::table('trip_data')->where('trip_country', '=' , $trip_country)->get();

But when i execute it i get above mentioned error. Any leads or suggestion will be highly appreciated.

0 likes
10 replies
vincent15000's avatar

get() returns a collection, so you need to retrieve the first() item of the collection.

$trip_country = DB::table('trip_data')->where('id',$request->people_near_by)->get(['trip_country'])->first()->trip_country;

You can also simplify the second query like this.

$all_trip = DB::table('trip_data')->where('trip_country', $trip_country)->get();
1 like
Sinnbeck's avatar

Just get the value

$trip_country = DB::table('trip_data')->where('id',$request->people_near_by)->value('trip_country');
 
2 likes
vincent15000's avatar

@Sinnbeck Oh so using value() allows to retrieve directly the specified field in the first model of the collection ?

1 like
Sinnbeck's avatar

@hamzaaslam I read a lot of code and follow several people on Twitter who give tips and tricks. And of course I pick up tricks in here from reading others suggestions

3 likes

Please or to participate in this conversation.