Sn0opr
Sn0opr

Reputation: 1026

Laravel 5: Get all passed data in view template

The objective is that I want to passe ALL passed data from the controller to the view in one single global JavaScript variable, this is an example:

In the controller

index(){
 return veiw('path.to.view', ['data1' => $data1, 'data2' => $data2]);
}

In the view

<script>
   var _backendData = {!! $allData !!}
   //$allData should contain ALL the passed data from the controller
</script>

I to store the all recieved data from controller in $allData

Upvotes: 4

Views: 1877

Answers (3)

Sougata Bose
Sougata Bose

Reputation: 31749

Set it on the controller - Use a multi-dimensional array to pass the data and get it in blade file.

return view('path.to.view', ['allData' => ['data1' => $data1, 'data2' => $data2]]);

Upvotes: 0

Margus Pala
Margus Pala

Reputation: 8663

When you are returning an array of data then you can access the elements one by one as shown below. You cannot just assign PHP array to be JavaScript array.

return view('path.to.view', [
   'allData' => ['data1' => $data1, 'data2' => $data2]
]);

View:

<script>
    var _backendData = {!! $allData['data1'] !!}
</script>

Upvotes: 0

lukasgeiter
lukasgeiter

Reputation: 152890

To access all that data, you pass it as one item of the root array. Because those keys become the view variables.

return view('path.to.view', [
   'allData' => ['data1' => $data1, 'data2' => $data2]
]);

View:

<script>
    var _backendData = {!! $allData !!}
</script>

However this is not going to work properly. You should use JSON to pass data to JavaScript:

var _backendData = JSON.parse("{!! json_encode($allData) !!}");

Upvotes: 2

Related Questions