Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populating js array in blade template

I'm trying to build a javascript array of data for use in flot from the result of a php DB query.

When I'm outputting numbers ($lic->Users) it's fine, but whenever I try to output a string I get a completely blank page in the browser.

I've tried:

  • {{ $lic->CompanyName }}
  • "<?php echo $lic->CompanyName; ?>"
  • {{{ $lic->CompanyName }}}
  • '"'+ <?php echo $lic->CompanyName; ?> +'"'

But when I hard-code it (to say, 'CompanyName'), it builds the bar graph (& displays the page) just fine.

var data = 
[
    @foreach($licdata as $lic)
    {
    'label': "{{ $lic->CompanyName }}",
    'data': [
                ["{{ $lic->CompanyName }}", {{ $lic->Users }}], 
                ["{{ $lic->CompanyName }}", {{ $lic->Emps }}]
            ]
    },
    @endforeach
];

I think it must be something to do with quoting/escaping the string in js, but I can't work out what, does anyone know what the correct syntax is?

like image 614
SteB Avatar asked Aug 26 '13 13:08

SteB


1 Answers

A better solution on the backend is to structure your data in an array, associated or otherwise.

Then return it:

return view( 'view_required',[
     'my_var'=> json_encode($array_or_object, JSON_UNESCAPED_SLASHES );
]);

on the front:

<script>
    var my_var = {!! $my_var !!};
</script>
like image 79
A H Bensiali Avatar answered Sep 22 '22 02:09

A H Bensiali