1

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)

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your reply. Please see my edit. Any idea why that error shows up?
You're welcome, googled a little i can see that the issue is related by forms but i can't find any quick answer, i suggest to add another question specific to this issue with clear description and more specific code.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.