Ahsan Imtiaz Ahsan Imtiaz - 2 months ago 4x
PHP Question

Cant access data retrieved from query in Laravel

This is my query:

$userInfo = DB::table('userinfo')
->where('user_id', $user->id)
->where('app_id', $appId)

When I am trying to display age_id:


It says "Undefined index: age_id"
Basically I have to use this age_id for another query, but I cannot figure out how to.


When you use the get method on the query builder like that it will return multiple rows rather than a single row. You could do something like this

foreach ($userInfo as $row) {
    echo $row->age_id;

Alternatively if you're expecting only one result to be returned you could use first.

$userInfo = DB::table('table')
    // Your wheres
if ($userInfo) {
    echo $userInfo->age_id;

Bear in mind this would add limit 1 to your query. If nothing was found then null would be returned.