Building a Vue SPA with Laravel Part 2

https://laravel-news.com/building-vue-spa-laravel-part-2/

In this tutorial, we continue Building a Vue single-page application (SPA) with Laravel by learning how to load async data from a Laravel API endpoint inside a Vue component. We will also look at error handling when an API response returns an error and how to respond in the interface.

If you didn’t read Part 1, we covered wiring up a Vue single page application (SPA) with Vue Router and a Laravel backend. If you want to follow along, you should go read through Part One first!

To keep the server-side data simple, our API will use fake data. In Part 3, we will convert the API to a controller with test data coming from a database.

The API Route

Vue SPA applications are stateless, meaning that we make API calls to the Laravel router with our routes defined in routes/api.php. The API routes don’t use session state, meaning our application is truly stateless on the backend.

In our example, let’s say we wanted to get a list of users that we can use to demonstrate making an asynchronous request to the backend from our Vue app:

1Route::get('/users', function () {2    return factory('App\User', 10)->make();3});

Our temporary route is using model factories to create a collection of Eloquent models that are not yet persisted to the database. We use make() method, which doesn’t attempt to insert the test data into the database, instead it returns a collection of new App\User instances that haven’t been persisted yet.

Defining a route in the routes/api.php file means our requests have a prefix of /api, because of the prefix defined in the app’s RouteServiceProvider class:

1protected function mapApiRoutes()2{3    Route::prefix('api')4         ->middleware('api')5         ->namespace($this->namespace)6         ->group(base_path('routes/api.php'));7}

Our user resource is GET /api/users and an example response might look like this:

 1[ 2   { 3      "name":"Roel Rosenbaum I", 4      "email":"catharine.kreiger@example.net" 5   }, 6   { 7      "name":"Prof. Clarissa Osinski", 8      "email":"wilfrid.kiehn@example.com" 9   },10   {11      "name":"Myrtle Wyman",12      "email":"dan31@example.com"13   },14   ...15]

The Client-Side Route

If you followed along in Part 1, we built a couple of routes in the resources/assets/js/app.js file to demonstrate navigating around the SPA. Any time we want to add a new route, we create new object in the routes array which define the path, name, and component of each route. The last route is our new /users route:

 1import UsersIndex from './views/UsersIndex'; 2 3const router = new VueRouter({ 4    mode: 'history', 5    routes: [ 6        { 7            path: '/', 8            name: 'home', 9            component: Home10        },11        {12            path: '/hello',13            name: 'hello',14            component: Hello,15        },16        {17            path: '/users',18            name: 'users.index',19            component: UsersIndex,20        },21    ],22});

The UsersIndex Component

The router defines a route using the UsersIndex component; here’s what the file (located at resources/assets/js/views/UsersIndex.vue) looks like:

 1<template> 2    <div class="users"> 3        <div class="loading" v-if="loading"> 4            Loading... 5        </div> 6 7        <div v-if="error" class="error"> 8            {{ error }} 9        </div>1011        <ul v-if="users">12            <li v-for="{ name, email } in users">13                <strong>Name:</strong> {{ name }},14                <strong>Email:</strong> {{ email }}15            </li>16        </ul>17    </div>18</template>19<script>20import axios from 'axios';21export default {22    data() {23        return {24            loading: false,25            users: null,26            error: null,27        };28    },29    created() {30        this.fetchData();31    },32    methods: {33        fetchData() {34            this.error = this.users = null;35            this.loading = true;36            axios37                .get('/api/users')38                .then(response => {39                    console.log(response);40                });41        }42    }43}44</script>

If you are new to Vue, there might be a couple of unfamiliar concepts here. I recommend reading the Vue components documentation and get familiar with the Vue lifecycle hooks (created, mounted, etc.).

In this component, we are fetching asynchronous data during the component created hook. We define a fechData() method which resets the error and users properties to null, sets loading to true.

The final line in the fetchData() method uses the Axios library to make the HTTP request to our Laravel API. Axios is a promise-based HTTP client, which we use to chain the then() callback where we log the response and will eventually set it to the users data property.

Here’s what the console data will look like if you load up /users in the application (the client-side page, not the API):

Another thing I would like you to pay attention to is the object destructuring going on here:

1<li v-for="{ name, email } in users">2    <strong>Name:</strong> {{ name }},3    <strong>Email:</strong> {{ email }}4</li>

Object destructuring is an efficient way of taking only the props needed for an object and is more concise/readable.

Finishing Up the Route Component

We have the route and component for /users, let’s hook up a navigation link in the main App component and then set the user data from the users response:

In resources/assets/js/views/App.vue, add a link using the route name we have the users index:

 1<template> 2    <div> 3        <h1>Vue Router Demo App</h1> 4 5        <p> 6            <router-link :to="{ name: 'home' }">Home</router-link> | 7            <router-link :to="{ name: 'hello' }">Hello World</router-link> | 8            <router-link :to="{ name: 'users.index' }">Users</router-link> 9        </p>1011        <div class="container">12            <router-view></router-view>13        </div>14    </div>15</template>16<script>17    export default {}18</script>

Next, let’s update the UsersIndex.vue file to set the user data:

 1fetchData() { 2    this.error = this.users = null; 3    this.loading = true; 4    axios 5        .get('/api/users') 6        .then(response => { 7            this.loading = false; 8            this.users = response.data; 9        });10}

Now if you refresh the page, you should see something like the following:

Dealing With Errors

Our component should work as expected most of the time, but we aren’t handling API errors yet. Let’s add a simulated server error to the API endpoint:

1Route::get('/users', function () {2    if (rand(1, 10) < 3) {3        abort(500, 'We could not retrieve the users');4    }56    return factory('App\User', 10)->make();7});

We use rand() to abort the request if the number is less than three. If you refresh the page a couple of times you should see the “Loading…”, and if you inspect the developer tools you’ll see an uncaught exception from the Axios request:

We can handle a failed request by chaining a catch() callback on the Axios promise:

 1fetchData() { 2    this.error = this.users = null; 3    this.loading = true; 4    axios 5        .get('/api/users') 6        .then(response => { 7            this.loading = false; 8            this.users = response.data; 9        }).catch(error => {10            this.loading = false;11            this.error = error.response.data.message || error.message;12        });13}

We set the loading data property to false and use the error exception to try to set a message key from the response. The message falls back to the exception.message property.

For good measure, let’s give the user a “Try Again” button on this condition within the UsersIndex.vue template, which simply calls our fetchData method to refresh the users property:

1<div v-if="error" class="error">2    <p>{{ error }}</p>34    <p>5        <button @click.prevent="fetchData">6            Try Again7        </button>8    </p>9</div>

Now if things fail, the UI should look like this:

Conclusion

In this short article, we added a new route to list out some fake users from a stateless Laravel API endpoint. We used an “after navigation” data fetching strategy to get the data. Or to put it another way, we requested the data from the API when the component is created.

In Part 3 we will look at using a callback in the Vue Router to fetch data before navigating to a component to show you how to fetch data before rendering a router view.

We will also convert the API to use a database table with seed data so we can go over navigating to an individual user which covers using router params.

Now, onward to Part 3 of Building a Vue SPA with Laravel!

Last updated