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

Share Me
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  

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

About code chef

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by code chef →