Standard PHP objects
The best way to provide PHP variables to JavaScript is json_encode
. When using Blade you can do it like following:
<script>
var bool = {!! json_encode($bool) !!};
var int = {!! json_encode($int) !!};
/* ... */
var array = {!! json_encode($array_without_keys) !!};
var object = {!! json_encode($array_with_keys) !!};
var object = {!! json_encode($stdClass) !!};
</script>
There is also a Blade directive for decoding to JSON
. I'm not sure since which version of Laravel but in 5.5 it is available. Use it like following:
<script>
var array = @json($array);
</script>
Jsonable's
When using Laravel objects e.g. Collection
or Model
you should use the ->toJson()
method. All those classes that implements the \Illuminate\Contracts\Support\Jsonable
interface supports this method call. The call returns automatically JSON
.
<script>
var collection = {!! $collection->toJson() !!};
var model = {!! $model->toJson() !!};
</script>
When using Model
class you can define the $hidden
property inside the class
and those will be filtered in JSON
. The $hidden
property, as its name describs, hides sensitive content. So this mechanism is the best for me. Do it like following:
class User extends Model
{
/* ... */
protected $hidden = [
'password', 'ip_address' /* , ... */
];
/* ... */
}
And somewhere in your view
<script>
var user = {!! $user->toJson() !!};
</script>