How to Convert Collection to Array in Laravel?

By Hardik Savani November 5, 2023 Category : Laravel

Hey Folks,

If you need to see an example of laravel convert collection to array. step by step explain how to convert collection to array in laravel. I explained simply step by step collection to array in laravel. This article will give you a simple example of laravel collection to array convert. follow the below example for convert collection to array laravel.

In this example, we will use toArray() and all() collection method to convert collection to array in laravel. we will see the simple three examples to convert collection to array in laravel.

Let's see the simple example with output:

Example 1: Laravel Convert Collection to Array using toArray()

you can see the simple controller file code:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UserController extends Controller

{

/**

* Display a listing of the resource.

*

* @return \Illuminate\Http\Response

*/

public function index(Request $request)

{

$myCollection = collect([1, 2, 3, 4, 5]);

$array = $myCollection->toArray();

dd($array);

}

}

Output:

array:5 [

0 => 1

1 => 2

2 => 3

3 => 4

4 => 5

]

Example 1: Laravel Convert Collection to Array using all()

you can see the simple controller file code:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UserController extends Controller

{

/**

* Display a listing of the resource.

*

* @return \Illuminate\Http\Response

*/

public function index(Request $request)

{

$myCollection = collect([1, 2, 3, 4, 5]);

$array = $myCollection->all();

dd($array);

}

}

Output:

array:5 [

0 => 1

1 => 2

2 => 3

3 => 4

4 => 5

]

Example 1: Laravel Convert Eloquent Collection to Array

you can see the simple controller file code:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UserController extends Controller

{

/**

* Display a listing of the resource.

*

* @return \Illuminate\Http\Response

*/

public function index(Request $request)

{

$users = User::select('id', 'name')->get();

$array = $users->toArray();

dd($array);

}

}

Output:

Array

(

[0] => Array

(

[id] => 1

[name] => Antonia Ortiz

)

[1] => Array

(

[id] => 2

[name] => Mohamed Hoeger

)

[2] => Array

(

[id] => 3

[name] => Pierce Towne

)

[3] => Array

(

[id] => 4

[name] => Prof. Vena Bernhard

)

)

I hope it can help you...

Shares