Jamie
Jamie

Reputation: 10886

Laravel & vue.js values to array

I'm using vue.js in Laravel.

I've 3 table's.

Article  
Location 
article_location (pivot table)

If I want to convert a location articles to json so I can pass it to vue How could I do this?

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

How could I do this?

EDIT --

Controller:

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

View:

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

Location model:

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

Error:

ErrorException in Macroable.php line 81: Method article does not exist. (View: /home/vagrant/Code/project/resources/views/locationproducts.blade.php)

Upvotes: 1

Views: 3023

Answers (1)

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

You could use toJson() method, to convert a model to JSON, you may use the toJson method. Like toArray, the toJson method is recursive, so all attributes and relations will be converted to JSON :

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

Hope this helps.

Upvotes: 1

Related Questions