1 - Pass Globally Using @json Directive
The easiest is to use the @json directive provided by the Laravel blade template. Instead of manually calling "json_encode", this directive is much more straightforward and intuitive to use. This method allows the variable to be accessible globally.
<script> window.posts = @json($posts); </script>
new Vue({ el: '#app', mounted() { console.log(window.posts); } })
2 - Directly Pass to Vue Component Props
The second method is to directly pass it into the Vue Component props. Imagine having a component called "post-item" that accepts "post" as its prop, you can write you code something like below.
<post-item :prop="@json($posts[0])">
3 - Pass the Data Directly inside the Vue Instance
You can also pass the data directly inside the Vue instance itself and since the Laravel blade template will be executed first, by the time the page load the data will already be present inside the Vue instance.
new Vue({ el: '#app', data() { return { posts: @json($posts) } }, mounted() { console.log(this.posts); } })
4 - Get Data through Laravel API
Define a new API route in Laravel and return the data to be consumed on the front-end.
# routes/api.php Route::get('posts', function () { return Post::all(); });
new Vue({ el: '#app', data() { return { posts: [] } }, mounted() { window.axios.get('/api/posts').then(res => { this.posts = res.data }) } })
5 - Laravel Broadcast
You can also make use of the Laravel data that are being broadcasted from the backend. Anything that goes from Laravel broadcast "broadcastWith" method will be returned as JSON to the front-end and you can consume it the same way as method number 4 above.
/** * Get the data to broadcast. * * @return array */ public function broadcastWith() { return ['id' => $this->user->id]; }