Home Javascript json_encode() is better then @json() in Blade Directive

json_encode() is better then @json() in Blade Directive

by Shahriar Sagor

In this laravel example i will discuss details about json encode in laravel blade application. Sometimes we need to pass an array to view with the intention of rendering it as JSON in order to initialize a JavaScript variable. On that time what we do ? Normally most of we use json_encode() method as like below.

<script>
    var app = < ? php echo json_encode($array); ? >;
</script

But do you know Laravel has a awesome blade directive for json_encode. You can use @json for do the same task what you do with json_encode fuction. Instead of manually calling function json_encode, we may use the @json Blade directive. The @json directive accepts the same arguments as PHP’s json_encode function as like bellow:

<script>
    var app = @json($array);

    var app = @json($array, JSON_PRETTY_PRINT);
</script>

so we can say that json_encode() is better then @json() in laravel Blade.

Read Also : How to Solve Target Class Does Not Exist In Laravel

I hope it will help you.For more you can follow us on facebook

close

You may also like