-3

Why laravel collection can use directly as a javascript variable but not a php array or object?

In testing.blade.php

<?php
use Illuminate\Support\Collection;
$testingArray = [1,2,3];
$testingObject = new stdClass();
$testingObject->testing = "Testing";
$testingObject->hello = "Hello";
$testingObject->bye = "Bye";
$testingCollection = Collection::make($testingArray);
?>

<script>
        var myArray = {!! $testingArray !!}; //Not work 
        var myObject = {!! $testingObject !!}; //Not work 

        var myArray = {!! json_encode($testingArray) !!}; //Work
        var myObject = {!! json_encode($testingObject) !!}; //Work
        var myCollection = {!! $testingCollection !!}; //Work
</script>

Any references?

Kenny
  • 55
  • 1
  • 9
  • https://stackoverflow.com/a/4885796/2075158 – Sachem May 14 '21 at 09:18
  • What happens between `{!! .. !!}` is *output*. PHP has no way of printing arrays and objects, because it hasn't got any instructions on how to turn them into a string. The Laravel Collection object probably has `__toString` implemented that allows the conversion. – El_Vanja May 14 '21 at 09:21
  • And [here it is](https://laravel.com/api/8.x/Illuminate/Support/Collection.html#method___toString), which points towards [this trait it's using](https://github.com/laravel/framework/blob/8.x/src/Illuminate/Collections/Traits/EnumeratesValues.php#L878). – El_Vanja May 14 '21 at 09:25
  • Don't forget the `@json` directive! – JustCarty May 14 '21 at 09:44

1 Answers1

1

This is because Collection objects are automatically serialised to JSON when you convert them to a string.

https://laravel.com/docs/8.x/eloquent-serialization#serializing-to-json says

models and collections are converted to JSON when cast to a string

This code you showed:

{!! $testingCollection !!}

tries to output $testingCollection to the view. Doing that obviously requires it to be turned into a string. This will automatically trigger its JSON serialisation, as per the documentation.

This happens via its standard __toString() function, which then points to a trait which calls toJSON() to perform the serialisation.

That in turn means that JavaScript can immediately read it, because as you're probably aware, valid JSON can be used as a JavaScript object literal (since JSON syntax is a subset of JS object syntax).

ADyson
  • 57,178
  • 14
  • 51
  • 63