Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a Laravel Collection/Array to a Javascript Array

I would like to assign an array from Laravel to a JavaScript array. I have gotten the array from my AppServiceProvider and json_decoded it like:

View::composer('*', function($view)
{
   $users = Users::all();
   $view->with(compact(users );
}

I then access my $usersArray from my javascript file like:

  var dataSet = JSON.parse({!!$users !!});

I am however getting the following error;

jQuery.Deferred exception: Unexpected token o in JSON at position 1 SyntaxError: Unexpected token o in JSON at position 1
at JSON.parse (<anonymous>)
like image 952
gerry Avatar asked Apr 07 '26 02:04

gerry


1 Answers

Since you're encoding it in the server side, you need to decode it in the client side like:

$chequesArray = Users::all()->toJson();

var dataSet = JSON.parse({!!json_encode($chequesArray)!!});

Or also Using "base64_encode" to conserve the json format like:

$chequesArray = base64_encode(Users::all()->toJson());

var dataSet = JSON.parse(atob('{{$chequesArray}}');

The main difference comes from the use of {{ }} vs {!! !!}, the first one escapes the special chars so it will turn the quotes "" to &quot; then the JS will be unable to parse the string (that why we can use `base64_encode``to conserve the format), the second one will conserve the format and allow the quotes what gives the JS part the ability to parse it simply.

like image 137
Zakaria Acharki Avatar answered Apr 09 '26 14:04

Zakaria Acharki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!