georgek's avatar

Get the first column data of first record

How can I get the first column data without know its name?

    $result = \DB::select($countQuery);
    echo $result[0]->email;

I need something like $results[0][0];

0 likes
7 replies
georgek's avatar

Also, how can I get the count without using ->get() at the end. $result->count() doesnt work :(

Lorceroth's avatar

By default, Laravel returns the results as stdClass objects. Go into app\config\database.php and change the fetch setting from:

'fetch' => PDO::FETCH_OBJ,

to

'fetch' => PDO::FETCH_NUM,

and you should be able to use

// First and second column
echo $result[0][0] . ' ' . $result[0][1];

:)

Lorceroth's avatar

You're welcome! :)

For your second question, you should append the aggregate function count() to the end of the query builder, rather than the end of your $result variable since it's impossible to call a method on an array type. And when you use PDO::FETCH_OBJ it's just a plain stdClass with props without any knowledge about a count() function.

$numberOfUsers = DB::table('users')->count();

echo 'Number of users: <i>' . $numberOfUsers . '</i>!';
$numberOfActiveUsers = DB::table('users')->where('active', 1)->count();

Good night :)

georgek's avatar

Well the thing is that the query I run its select count(*) from table where... So it returns just a one record and one column with the total number of records. I want to know the count of records just to make sure I received back a record. I understand that count will not work with the object but what if I make the change you suggested, will it work as count($result) properly?

Lorceroth's avatar

http://php.net/manual/en/function.count.php

If you change to PDO::FETCH_NUM, the return type will be a two-dimensional array like $result[row][column].

By default, count($arr) will not count the elements in recursive-mode, which means it won't count the columns in the array, just the rows. :)

1 like

Please or to participate in this conversation.