By John Koster
The jsonSeralize
method internally returns the value of the toArray
method. This method exists to implement PHP's JsonSerializable
interface, which allows developers to customize how a class is represented when using the json_encode
function.
#Signature
The signature of the jsonSerialize
method is:
1public function jsonSerialize();
#Example Use
The following example demonstrates the jsonSerialize
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 a value that can be converted to JSON.
11$messages = $messageBag->jsonSerialize();
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'
∎