herhuf
herhuf

Reputation: 517

Laravel + Vue - Pass multidimensional PHP array to vue component

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?

Upvotes: 1

Views: 506

Answers (2)

user8718268
user8718268

Reputation:

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);

Upvotes: 0

Rooneyl
Rooneyl

Reputation: 7902

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.

Upvotes: 2

Related Questions