David Robles
David Robles

Reputation: 31

error when receiving an array from the controller in a javascript function in project laravel

I get an error "htmlspecialchars () expects parameter 1 to be string, array given". I am passing an array from the controller to the view and trying to collect it in a javascript function, Thank you very much for your help.

Code controller

$etis = EtiquetaPresupuesto::where('presupuestos_id', $id)->get();
$idEtiquetas=[];

foreach ($etis as $eti) {
    array_push($idEtiquetas, $eti->etiquetas_id);
}

return view('presupuestos_contabilidad/info-presupuestos', [
    'etiquetas_id' => $idEtiquetas,
]);

Code javascript in view

function etiquetas_sesion(){
    var array_etiquetas = {{$etiquetas_id}};
}

Upvotes: 0

Views: 45

Answers (2)

Martin Heralecký
Martin Heralecký

Reputation: 5779

$etiquetas_id in your code is an array, but you're trying to print it as string via {{ }}, which escapes it through htmlspecialchars().

If you want the array to be preserved in JavaScript (as JavaScript array), use json_encode():

var array_etiquetas = {!! json_encode($etiquetas_id) !!};

Upvotes: 1

Malkhazi Dartsmelidze
Malkhazi Dartsmelidze

Reputation: 4992

You must use json_encode() function to get array or object.

Also you can use @json() blade selector

For example:

function etiquetas_sesion(){
    var array_etiquetas = @json($etiquetas_id);
}
function etiquetas_sesion(){
    var array_etiquetas = {!! json_encode($etiquetas_id) !!}
}

Upvotes: 3

Related Questions