Laravel Convert Collection To Associative Array

April 20, 2023 | Category : Other

Hi Dev,Hi Artisan,
Now, let's see a tutorial of laravel convert collection to array. let’s discuss about laravel convert collection to associative array. I explained simply about laravel convert eloquent collection to array. If you have a question about laravel convert resource collection to array then I will give a simple example with a solution.

Here, i will show you two simple example of how to onvert collection to array in laravel application. one simple convert collection object to array using toArray()

and next example will eloquent resource to array using pluck() and toArray().

so, let's see simple examples. you can use this example in laravel 6, laravel 7, laravel 8, laravel 9 and laravel 10 versions.

Example 1:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class PostController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index(Request $request)

{

$collection = collect([1, 2, 3]);

$arrayColection = $collection->toArray();

dd($collection, $arrayColection);

}

}

Output:

Example 2:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\User;

class PostController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index(Request $request)

{

$users = User::query()->take(5)->get();

$usersArray = $users->toArray();

dd($users, $usersArray);

}

}

Output:

I hope it can help you...