Laravel Convert Collection to Array Example

By Hardik Savani April 16, 2024 Category : Laravel

Hi Dev,

This post will give you an example of laravel convert collection to array. I would like to show you laravel convert collection to associative array. you will learn laravel convert eloquent collection to array. This post will give you a simple example of laravel convert resource collection to array. Alright, let’s dive into the steps.

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, laravel 10 and laravel 11 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...

Tags :
Shares