phplaravellaravel-blade

laravel how to add element to array in the blade template


I wanna add elements to the array in laravel blade template. here is my script:

<script>
  selected_arr = [];
</script>

I wanna get an array like [1,2,3], I tried to use array_push, the code is here:

<script>
  function select_array (id){
    selected_arr=array_push(selected_arr, id);
  }
</script>

the result of selected_arr is still null. Can you please help me to figure it out? Many Thanks!

Edit: here is my controller function:

$selected_arr=$request->selected_arr;
$selected_arr=implode(",", $selected_arr);

here is my updated script (I wanna use this example to have a try first):

<script>
  selected_arr = [];
  selected_arr.push(1);
</script>

the error message is:

implode():Argument #2 ($array) must be of type ?array, string given


Solution

  • If you need to share data with the server you need a controller behind it, then you need ajax calls to sync view variables with the contoller. In this case you can use Laravel Jestream to have an integrated scaffold with Livewire and AlpineJS

    If you only need the array variable on client side you can use javascript (so you can reference the js docs from now on) function like

       selected_arr.push(id)