Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.1 DB:select toArray()

I have a large SQL statement that I am executing like so:

$result = DB::select($sql); 

For example

$result = DB::select('select * from users'); 

I'd like the result to be an array - but at the moment it returns a structure like so, an array with Objects...

Array (     0 => stdClass::__set_state(array(         'id' => 1,         'first_name' => 'Pavel',         'created_at' => '2015-02-23 05:46:33',     )),     1 => stdClass::__set_state(array(         'id' => 2,         'first_name' => 'Eugene',         'created_at' => '2016-02-23 05:46:34',     )), ...etc... 

)

like image 430
Yevgeniy Afanasyev Avatar asked May 30 '16 04:05

Yevgeniy Afanasyev


People also ask

What is toArray in Laravel?

toArray is a model method of Eloquent, so you need to a Eloquent model, try this: User::where('name', '=', 'Jhon')->get()->toArray(); http://laravel.com/docs/eloquent#collections. Follow this answer to receive notifications.

How do you get Join results as an array of objects in Laravel?

$shop = Shop::leftJoin('ratings', 'ratings. shop_id', '=', 'shops.id') ->select('shops. *', 'ratings. rating')->get(); return response($shop);

What does get () do in Laravel?

This allows you to add conditions throughout your code until you actually want to fetch them, and then you would call the get() function. Think of it like this: when you don't exactly know what a query will return then you need to use get() .

How can we get data from database in controller in Laravel?

After configuring the database, we can retrieve the records using the DB facade with select method. The syntax of select method is as shown in the following table. Run a select statement against the database.


1 Answers

Seems like you need to cast the stdClass Objects as Array so you can have the structure you are looking for

$result = array_map(function ($value) {     return (array)$value; }, $result); 
like image 192
Jose Mujica Avatar answered Sep 18 '22 09:09

Jose Mujica