Laravel 10 Convert Collection to Array Example Tutorial

May 05, 2023 . Admin



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.

In this piece, I'll show you two straightforward examples of how to do it in a Laravel programme. The simple function ToArray() can be used to turn collection objects into arrays. The next example converts an eloquent resource to an array using the functions 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:
Illuminate\Support\Collection {#420
  #items: array:3 [    0 => 1    1 => 2    2 => 3  ]
}
array:3 [
  0 => 1
  1 => 2
  2 => 3
]	
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...

#Laravel 10