Laravel output:
Array
(
[0] = stdClass Object
(
[ID] = 5
)
[1] = stdClass Object
(
[ID] = 4
)
)
$res = ActivityServer::query()->select('channel_id')->where(['id' => $id])->first()->attributesToArray();
I use get()
, it returns an object, I use the attributesToArray()
to change the object attribute to an array.
Object to array
$array = (array) $players_Obj;
$object = new StdClass;
$object->foo = 1;
$object->bar = 2;
var_dump( (array) $object );
Output:
array(2) {
'foo' => int(1)
'bar' => int(2)
}
I suggest you simply do this within your method
public function MyAwesomeMethod($returnQueryAs = null)
{
$tablename = 'YourAwesomeTable';
if($returnQueryAs == 'array')
{
DB::connection()->setFetchMode(PDO::FETCH_ASSOC);
}
return DB::table($tablename)->get();
}
With this all you need is to pass the string 'array' as your argument and Voila! An Associative array is returned.
UPDATE since version 5.4 of Laravel it is no longer possible.
You can change your db config, like @Varun suggested, or if you want to do it just in this very case, then:
DB::setFetchMode(PDO::FETCH_ASSOC);
// then
DB::table(..)->get(); // array of arrays instead of objects
// of course to revert the fetch mode you need to set it again
DB::setFetchMode(PDO::FETCH_CLASS);
For New Laravel above 5.4 (Ver > 5.4) see https://laravel.com/docs/5.4/upgrade fetch mode section
Event::listen(StatementPrepared::class, function ($event) {
$event->statement->setFetchMode(...);
});
Just in case somebody still lands here looking for an answer. It can be done using plain PHP. An easier way is to reverse-json the object.
function objectToArray(&$object)
{
return @json_decode(json_encode($object), true);
}
Its very simple. You can use like this :-
Suppose You have one users table and you want to fetch the id only
$users = DB::table('users')->select('id')->get();
$users = json_decode(json_encode($users)); //it will return you stdclass object
$users = json_decode(json_encode($users),true); //it will return you data in array
echo '<pre>'; print_r($users);
Hope it helps