How to transform the collection into an array Laravel

Transform a Laravel collection into an array with examples: learn how to use the toArray() helper & other methods to manipulate your data.

Transforming a collection into an array in Laravel is a fairly straightforward process. To do this, we can use the "toArray()" method, which will take the collection and return an array containing all of its elements.

Example

Let's take a look at an example of transforming a collection into an array. Suppose we have a collection called "myCollection" which contains the following elements:


myCollection = [
  {
    "name": "John",
    "age": 25
  },
  {
    "name": "Jane",
    "age": 30
  },
  {
    "name": "Bob",
    "age": 20
  }
];

To transform the collection into an array, we can use the "toArray()" method as follows:


myArray = myCollection.toArray();

This will return an array with all of the elements from the collection:


myArray = [
  {
    "name": "John",
    "age": 25
  },
  {
    "name": "Jane",
    "age": 30
  },
  {
    "name": "Bob",
    "age": 20
  }
];

And that's it! Transforming a collection into an array in Laravel is a simple and straightforward process.

Answers (0)