Laravel & vue.js 值到数组


Laravel & vue.js values to array

我在Laravel中使用vue.js。

我有 3 张桌子。

Article  
Location 
article_location (pivot table)

如果我想将位置文章转换为 json,以便我可以将其传递给 vue 我该怎么做?

 <div class="container">
        Location->article  //all articles of a location to json
        <template id="ln-data">
            <ul>
                <li v-for="value in list">
                    @{{ value.name }}
                </li>
            </ul>
        </template>
        <script>
        Vue.config.debug = true;
        Vue.component('data', {
            template: '#ln-data',
            props:['list'],
            created() {
                this.list = JSON.parse(this.list);
            }
        })
        new Vue({
            el: 'body'
        });
        </script>

我该怎么做?

编辑--

控制器:

$location = location::all();
return view('locationproducts')->with('location',$location);

视图:

  <div class="container">
            <data list="{{ $location->article()->toJson() }}"></data>
    </div>

位置模型:

public function article()
{
    return $this->belongsToMany('App'article','article_location');
}

错误:

Macroable中的错误异常.php第 81 行:方法文章不 存在。(查看: /home/vagrant/Code/project/resources/views/locationproducts.blade.php)

您可以使用

toJson()方法,要将模型转换为 JSON,您可以使用 toJson 方法。像toArray一样,toJson 方法是递归的,所以所有属性和关系都会转换为 JSON:

$location->articles()->toJson();

希望这有帮助。