Hello to all, welcome to therichpost.com. In this post, I will tell you, How to Handling Laravel 5.7 API data with Vue.js Fetch API?
Vue.js is growing very fast these days and Laravel 5.7 has been released now. Both are very powerful on there area. Vue.js is getting more response because of its clean coding structure and easy to understand.
If you have knowledge of Html and javascript then you can easily learn this.
The best thing, I like this about Vue.js is, we don’t need to install complete folder like Angular, we just need to Vue.js CDN and start coding.
Laravel 5.7 also came with some great new features. I personally like laravel because of its flexible features and greate online supports.
Here is the working image fetching data and I am showing this data in console:
Here, I am going to tell you how all the code works:
1. Here is code for Veu.js and I have added this into html file with Veu.js cdn file:
In this file, I have used Veu.js Fetch API used to get the data without use of third party resource. Fetch is similar to XMLHttpRequest (XHR) but Fetch is better because we just want to request a URL, get a response and parse it as JSON.
<div id="app"> <ul> <li v-for="user in users"> {{ user }} </li> </ul> </div> <script src="https://cdn.jsdelivr.net/npm/vue"></script> <script> var app = new Vue({ el: '#app', data: { users: [] }, created () { fetch("http://localhost/blog/public/api/sample-restful-apis") .then(response => response.json()) .then(json =>{ this.users = json console.log(this.users); }) } }) </script>
2. Here is the laravel api code and you need to add this into your laravel 5.7 routes/api.php file:
In this file, we write the api route path.
<?php use Illuminate\Http\Request; /* |-------------------------------------------------------------------------- | API Routes |-------------------------------------------------------------------------- | | Here is where you can register API routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | is assigned the "api" middleware group. Enjoy building your API! | */ Route::get('sample-restful-apis', function() { return response()->json([ 'name' => 'therichpost', 'domain' => 'therichpost.com' ]); });
And you are done, if you have any query related to this post, then you can questions or comment below.
Recent Comments