Ahsan Imtiaz Ahsan Imtiaz - 3 months ago 9
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)
->select('age_id','sex_id')->get();


When I am trying to display age_id:

dd($userInfo['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.

Answer

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
    ->first();
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.

Comments