In this article, we will learn how to convert a Laravel collection to an array method.

For some reason, the Laravel collection to array (toArray method) will allow us to transform into a simple PHP array so that we may access the record through an array.

I'll demonstrate numerous examples of the Laravel collection array in this tutorial.

Let's see an example:

public function collectoToArray()
{
    $data = collect([
        'name' => 'Raihan Haque', 
'phone' => '+8801737770973', 
'email' => 'raihan.pust@gmail.com',
'gender' => 'male',
'age' => 20
]);
    return $data;
}
Output : 
Array
(
'name' => 'Raihan Haque', 
'phone' => '+8801737770973', 
'email' => 'raihan.pust@gmail.com',
'gender' => 'male',
'age' => 20
);

As you can see, we use the method toArray() to ensure that the desired array is returned.


Similar Way, we convert array collection into JSON format using toJson method

Let's see an example:


public function collectoToArrayJson()
{
    $data = [
'name' => 'Raihan Haque', 
'phone' => '+8801737770973', 
'email' => 'raihan.pust@gmail.com',
'gender' => 'male',
'age' => 20
];
#array convert into collection
$collectoToArrayJson = collect($data);
return $collectoToArrayJson->toJson();
}

Output : 
{
"name": "Raihan Haque",
"phone": "+8801737770973",
"email": "raihan.pust@gmail.com",
"gender": "male",
"age": 20
}


This ways we can convert array to collection, collection to array and collection to JSON format.

Hope this article will help you to know how to convert laravel collection to array or json

Share