2

I'm facing this problem when use database in Laravel. How can i convert that to Array the most simpletest?

$data = DB::table('users')->get();
2
  • Why not using Laravel Models? In that way you'll end up with a collection of results including the toArray() method which converts the full array (and children) to an array. Commented Mar 1, 2018 at 10:34
  • I think so too. Commented Mar 1, 2018 at 10:38

4 Answers 4

6

Please try this. this will return array of objects.

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

*Updated

if you want to convert all nested properties to the array, try this.

$result = json_decode(json_encode($data, true), true);
Sign up to request clarification or add additional context in comments.

3 Comments

This will return an array of objects.
json_decode(json_encode($data, true), true); This will return array of arrays.
The comment by Sumit just above works for me, in fact... it's the correct answer.
5

get() will return a collection. If you want to get an array of objects, use the toArray() method:

$data->toArray();

If you want to convert every object to an array too, do this:

$data->map(function($i) {
    return (array)$i;
})->toArray();

Comments

0

I usually run into this problem when I use DB::select and manually write my sql:

    $sql = 'SELECT *
                FROM ba_pics ba
                INNER JOIN pages pgs
                    ON ba.service_page_id = pgs.id';

    $baPics = DB::select($sql);
    $baPics = json_decode(json_encode($baPics, true), true);


    return view('beforeAndAfter',['baPics'=>$baPics, 'lodata'=>'no lodata yet']);

Here is another way using PHP's array_map function:

    $sql = 'SELECT *
                FROM ba_pics ba
                INNER JOIN pages pgs
                    ON ba.service_page_id = pgs.id';

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

    $baPics = array_map(function($i) {
        return (array)$i;
    }, $baPics);

    return view('beforeAndAfter',['baPics'=>$baPics, 'lodata'=>'no lodata yet']);

Comments

0

My 2 cents, I just did it today:

DB::table('my_table')->get()->map(fn($item) => (array) $item)->toArray();

This will return an array of rows, where each row is an array itself.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.