How to retrieve a result set from a raw query as an array instead of an object in Laravel 3 How to retrieve a result set from a raw query as an array instead of an object in Laravel 3 laravel laravel

How to retrieve a result set from a raw query as an array instead of an object in Laravel 3


You may also get all the result always as array by changing

application/config/database.php

'fetch' => PDO::FETCH_CLASS,

on line 31 to

'fetch' => PDO::FETCH_ASSOC,


Original answer for Laravel 3

Eloquent has a method to_array()

From docs:

The to_array method will automatically grab all of the attributes on your model, as well as any loaded relationships.

$user = User::find($id);return Response::json($user->to_array());

or

return Response::eloquent($user);

If you are using fluent, you can do as Sinan suggested and change the global configuration to return an associative array rather than objects.

Alternatively, you can convert an object to and from JSON to convert it to an array although the global option would be preferable in most cases. You can use the following in projects where you prefer objects normally but in certain edge cases need an array. This method will not play well with Eloquent, use the methods above in that case.

$users = DB::table('users')->where('name', '=', 'david')->get();return array_map(function($val){    return json_decode(json_encode($val), true)}, $users);

Another option would be to temporarily change the runtime configuration

Config::set('database.fetch', PDO::FETCH_ASSOC);

For Laravel ~4

In Laravel 4 onwards, all method names conform to PSR-2 standards.

$user = User::findOrFail($id);return Response::json($user->toArray());// In Laravel 5 onward the functions are preferred to facades.return response()->json($user->toArray());


I don't know if laravel has in built function for returning results as array but if not you can use this snippet:

Where $data is your returned array of objects

$data = json_decode(json_encode((array) $data), true);