gerry
gerry

Reputation: 127

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>)

Upvotes: 3

Views: 3095

Answers (2)

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

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.

Upvotes: 7

narayansharma91
narayansharma91

Reputation: 2353

var dataSet = @php $chequesArray @endphp;

Upvotes: -2

Related Questions