Rushikesh Akhare
Rushikesh Akhare

Reputation: 91

Laravel variable value being lost when passing to a function

$country = DB::table('location_countries')->where('name','India')->first();
$country_id = $country['_id'];
echo $country_id;
$states = DB::table('location_states')->where('country_id',$country_id)->first();
echo $states['name'];

above is the code i am running in the controller i have used jenseggers/mongodb for the mongodb connection.

till this part of code i can see the response when i do the echo

$country = DB::table('location_countries')->where('name','India')->first();
$country_id = $country['_id'];
echo $country_id;

after i pass the $country_id to the function as below it shows no response

$states = DB::table('location_states')->where('country_id',$country_id)->first();
echo $states['name'];

if i directly pass the string like the below code instead of passing the $country_id variable then i get a response but if i pass a variable there is no response.

$states = DB::table('location_states')->where('country_id','value-here')->first();

Why is this happening and how to bypass this.

Upvotes: 1

Views: 230

Answers (1)

Niklesh Raut
Niklesh Raut

Reputation: 34914

Query returns an object not an array so use it like this:

If you want to retrieve the id column: $country->id;

The same is true for states, e.g., the name column: $states->name;

Also try with trim maybe there is any blank space:

where('country_id', trim($country_id)) 

Upvotes: 2

Related Questions