Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove &quot from json using laravel

Hello I wanted to know how to use blade variable in javascript. here is my query in laravel

$users=json_encode(DB::table('ledger')->select('name','openingbalance')->get());

I'm trying to access this in my javascript file like shown below

var users ="{{ $users }}";

and I get output as shown below:

[
      {"name":"Harsh","openingbalance":"5755.00"},      
      {"name":"Harh","openingbalance":"-12000.00"},
      {"name":"gfgfhgf","openingbalance":"-333.00"}
]

I wanted to know how to remove &quot so i get a perfect json to use.

like image 504
Harsh Makadia Avatar asked Sep 06 '25 03:09

Harsh Makadia


2 Answers

You're escaping the data with {{ }} automatically in Laravel 5. Use {!! $users !!} instead.

like image 155
Joel Hinz Avatar answered Sep 07 '25 20:09

Joel Hinz


Rendering JSON

Sometimes you may pass an array to your view with the intention of rendering it as JSON in order to initialize a JavaScript variable. For example:

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

However, instead of manually calling json_encode, you may use the @json Blade directive. The @json directive accepts the same arguments as PHP's json_encode function. By default, the @json directive calls the json_encode function with the JSON_HEX_TAG, JSON_HEX_APOS, JSON_HEX_AMP, and JSON_HEX_QUOT flags:

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

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

You should only use the @json directive to render existing variables as JSON. The Blade templating is based on regular expressions and attempts to pass a complex expression to the directive may cause unexpected failures.

Source: documentation

like image 24
chebaby Avatar answered Sep 07 '25 20:09

chebaby