Search

Laravel 5 Message Bags: Converting the Message Bag to an Array With toArray

April 21, 2018 —John Koster

The toArray method can be used to retrieve the MessageBag instance as an array. It internally accomplishes this by returning a call to the getMessages method.

#Signature

The signature of the toArray method is:

1public function toArray();

#Example Use

The following example demonstrates the usage of the toArray method:

1use Illuminate\Support\MessageBag;
2 
3// Create a new MessageBag instance.
4$messageBag = new MessageBag;
5 
6// Add new messages to the message bag.
7$messageBag->add('hello', 'The first message bag message');
8$messageBag->add('world', 'The second message');
9 
10// Get an array of all the messages.
11$messages = $messageBag->toArray();

After the above code has executed, the $messages variable will be an array and contain a value similar to the following output:

1array
2 'hello' =>
3 array
4 0 => string 'The first message bag message'
5 'world' =>
6 array
7 0 => string 'The second message'