Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DB query builder toArray() laravel 4

I'm trying to convert a query to an array with the method toArray() but it doesn't work for the query builder. Any ideas for convert it?

Example

DB::table('user')->where('name',=,'Jhon')->get()->toArray(); 
like image 481
Fabrizio Fenoglio Avatar asked Dec 25 '13 20:12

Fabrizio Fenoglio


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.

What is Query Builder in laravel?

Laravel's database query builder provides a convenient, fluent interface to creating and running database queries. It can be used to perform most database operations in your application and works perfectly with all of Laravel's supported database systems.

How do you pluck in laravel?

While developing in eloquent, the column name can be passed as an argument in order to extract the values. Pluck () also accepts a second argument and if it happens to be an Eloquent collection, it will be another column name. To further strengthen the pluck() function, the wherein() function can be used.

IS NOT NULL laravel?

Check if not null: whereNotNullSELECT * FROM users WHERE last_name IS NOT NULL; The equivalent to the IS NOT NULL condition in Laravel Eloquent is the whereNotNull method, which allows you to verify if a specific column's value is not NULL .


2 Answers

If you prefer to use Query Builder instead of Eloquent here is the solutions

$result = DB::table('user')->where('name',=,'Jhon')->get(); 

First Solution

$array = (array) $result; 

Second Solution

$array = get_object_vars($result); 

Third Solution

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

hope it may help

like image 179
Somwang Souksavatd Avatar answered Nov 15 '22 06:11

Somwang Souksavatd


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

like image 39
petkostas Avatar answered Nov 15 '22 06:11

petkostas