Laravel MessageBag Public API: toArray

November 29, 2016 —John Koster

The toArray method is similar to the all method in that it will return the underlying array that the collection instance is using. The difference, however, is that the toArray method will convert any object instance it can into arrays (namely any object that implements the Illuminate\Contracts\Support\Arrayable interface). Consider the following code:

1<?php
2 
3use Illuminate\Support\Collection;
4 
5$items = [
6 'first' => 'I am first',
7 'second' => 'I am second',
8 'third' => new Collection([
9 'first' => 'I am nested'
10 ])
11];
12 
13$collection = Collection::make($items);
14 
15$returnedItems = $collection->toArray();

After the above code has executed, the $returnedItems variable would contain a value similar to the following output:

1array (size = 3)
2 'first' => string 'I am first' (length=10)
3 'second' => string 'I am second' (length=11)
4 'third' =>
5 array (size=1)
6 'first' => string 'I am nested' (length=11)

#Continue Reading

This article is the start of a mini-series about Laravel's ErrorMessageBag component. Click through the rest of the articles to continue reading:

Some absolutely amazing
people

The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.