Reputation: 829
I have a controller which passes an array data to view. Inside the view, I wanted to use the data as string in JSON object format.
Here is my controller:
class TestController extends Controller
{
private $user;
public function index()
{
return view('app')->with([
'userdata' => array('user' => 'John', 'age' => 20),
'access_token' => 'token_here'
]);
}
}
Here is my view app.php
<html>
<-- more html codes--->
<script>
let userdata = "{{ $userdata }}"; // ERROR: htmlspecialchars() expects parameter 1 to be string, array given
</script>
<-- more html codes--->
</html>
I tried using implode,
<script>
let userdata = "{{ implode(' ', $userdata)";
console.log(userdata);
</script>
It didn't have an error, but the problem is, the result becomes:
{"userdata":{"user" .....}
How can I have a correct result like this:
{'userdata': {'user':'john', 'age': 20}...} // this should be a string
Does anybody know?
Upvotes: 1
Views: 882
Reputation: 4992
You can use json_encode
:
{!! json_encode($userdata) !!}
note that you have to use
{!! !!}
to get exact string what you want. strings placed in{{ }}
are escaped
Also you can user blade directive @json
. depends which version of laravel you are using:
@json($userdata)
Upvotes: 3
Reputation: 125
From Laravel blade docs.
Rendering JSON
Sometimes you may pass an array to your view with the intention of rendering it as JSON in order to initialize a JavaScript variable. For example:
<script>
var app = <?php echo json_encode($array); ?>;
</script>
However, instead of manually calling json_encode, you may use the @json Blade directive. The @json directive accepts the same arguments as PHP's json_encode function:
<script>
var app = @json($array);
var app = @json($array, JSON_PRETTY_PRINT);
</script>
Upvotes: 1