How to Convert Collection to Array in Laravel 10?
Hi dev,
This article will show you how to convert a collection to an array using Laravel. I'd want to demonstrate how to transform a collection in Laravel to an associative array. You'll learn how to convert an eloquent collection to an array in Laravel. You'll find a straightforward example of how to convert a resource collection to an array in this post. Let's get started with the steps now.
In this section I'll provide you two simple instances of how to convert a collection to an array in a Laravel program. ToArray() is a straightforward method for converting collection objects to arrays. The next example uses pluck() and toArray() to convert an eloquent resource to an array.
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
- How to Notifications With database Driver in Laravel 11?
- How to Send Email Via Notification in Laravel 11?
- How to Install and Configure Laravel 11 Debugbar?
- How to Like Dislike System in Laravel 11?
- How to Paginate a Model with Relationship in Laravel 11?
- Laravel 11 Upload Files to Amazon S3 Example
- Laravel 11 Send WhatsApp Messages Example
- Laravel 11 Rest API Authentication Using JWT Tutorial