There are 5 ways to pass data from Laravel to Vue Js components and you will learn all of them in this post. So let's get started and get them covered.
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.
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>
Then in your Vue Js mount method, you can access the "posts" variable as necessary.
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(); });
In the Vue instance, you can perform the ajax call to retrieve the data. In this example, it's using axios library.
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]; }
By now you should know all the 5 different ways to pass data from Laravel backend to Vue Js. Hopefully, this tutorial is helpful for you, and don't forget to share it with your friends. Cheers and happy coding.
Leave a reply