1

In the file config/variables.php I have defined the following objects as a multidimensional array:

<?php

return [
    [
        'name' => 'test1',
        'surname' => 'test1'
    ],
    [
        'name' => 'test2',
        'surname' => 'tes2'
    ],
    [
        'name' => 'tes3',
        'surname' => 'test3'
    ]
];

I want to use this data in a Vue component, for example like this:

<template>
    <div>
        <div>Items:</div>
        <div v-for="i of items">
            {{ i.name }} {{ i.surname }}
        </div>
    </div>
</template>

<script>
export default {
    name: "Test",
    props: {
        items: []
    }
}
</script>

I bring component and data together in a blade template that contains, among other, this:

<div>Begin of test</div>
<Test :items="@json(Config::get('variables'))"></Test>
<div>End of test</div>

I would expect Laravel to pass the data on to the component which then renders a simple page containing the divs with the provided data. What I actually see in the browser is this:

<div>Begin of test</div>
":"test1","surname":"test1"},{"name":"test2","surname":"tes2"},{"name":"tes3","surname":"test3"}]"="">
<div>End of test</div>

For one the data seems to get garbled in the process. Also the <div>Items:</div> of the component does not appear at all. So it seems the @json call somehow breaks the entire component. Same behaviour using {!! json_encode(Config::get('variables')) !!} instead. When I just output the config values directly into a div like <div>@json(Config::get('variables'))</div> the complete array is cleanly printed as JSON.

Why does this happen and how can I fix it?

2 Answers 2

2

You are almost there!
You have just forgotten to escape the PHP in the element in your blade view.
It should be;

<div>Begin of test</div>
<Test :items="{{ json_encode(Config::get('variables')) }}"></Test>
<div>End of test</div>

If you want to use teh @json tag you need to drop the double quotes. Example;

<div>Begin of test</div>
<Test :items=@json(Config::get('variables'))></Test>
<div>End of test</div>

I'm no JS expert, but I think this is due to when passing to :items (a shortcut for v-bind) it is treated as a JavaScript expression.

2
  • I'm stunned. Thought I tried everything. But why is it working with @json in a regular div then? Thank you, this solves it. Will accept as soon as I can.
    – herhuf
    Commented Sep 10, 2021 at 7:55
  • 1
    @herhuf you can use the @json tag, answer updated
    – Rooneyl
    Commented Sep 10, 2021 at 8:35
0

Update your variables.php

$return = array(
  array(
   'name' => 'test1',
   'surname' => 'test1'
  ),
  array(
  'name' => 'test2',
   'surname' => 'tes2'
  ),
  array(
  'name' => 'tes3',
  'surname' => 'test3'
  )
);

echo json_encode($return);

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.