Laravel convert collection to array example

In this article explain of laravel convert collection to array. I have a explain how to convert collection to array in laravel. This article will give you a simple example of laravel collection to array convert. You can convert a collection to an array using the toArray() method. This method available on all collection and can be applied to any Laravel collection.

How to convert collection to array in Laravel?

When working with models in laravel, the results are often returned as collection. Collections are offer a variety of methods for manipulating data, When you might want to convert collection to a simple PHP array. We’ll look at how to achieve that using the toArray() method and other relevant approaches.

In this example, we will explain and use toArray() and all() collection method to convert collection to array in laravel.

Let’see the below example with output:

Example 1: Laravel convert collection to array using method toArray()
$collection = collect([1, 3, 5, 7, 9]);

$arrayValue = $collection->toArray();

dd($arrayValue);
Output:
arrat:5 [
    0 => 1
    1 => 3
    2 => 5
    3 => 7
]
Convert a collection to an array

Laravel collection can be converted into array using the toArray() method. This method works on any instance of Illuminate\Support\Collection or eloquent collections.

$data = Description::all(); // Return collection of all description
$dataArray = $data->toArray(); // Convert collection to an array

In this example we are fetching all description from the Description model using the all() method, which returns of collection then using toArray() method converts the collection into a PHP array.

Convert a collection of specific columns

You can see the below example and used the laravel convert collection to array.

$data = Description::select('title', 'detail')->get();

$dataArray = $data->toArray();

This will return an array of description with only the title and detail field.

Convert a collection after filtering

If you need to filter a collection and then convert it to an array, you can follow below method and then call toArray().

$data = Description::all()->filter(function ($description) {
    return $description->is_valid;
});

$dataArray = $data->toArray();

In this example, only valid description are filtered out and the filtered collection is converted into an array.

I hope this tutorial help you.

Leave a Reply

Your email address will not be published. Required fields are marked *