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 " so i get a perfect json to use.
You're escaping the data with {{ }}
automatically in Laravel 5. Use {!! $users !!}
instead.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With