Laravel Idea for PhpStorm - Full-featured IDE for productive artisans!

Building a Vue SPA with Laravel Part 2

Published on by

Building a Vue SPA with Laravel Part 2 image

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:

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

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:

protected function mapApiRoutes()
{
Route::prefix('api')
->middleware('api')
->namespace($this->namespace)
->group(base_path('routes/api.php'));
}

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

[
{
"name":"Roel Rosenbaum I",
"email":"catharine.kreiger@example.net"
},
{
"name":"Prof. Clarissa Osinski",
"email":"wilfrid.kiehn@example.com"
},
{
"name":"Myrtle Wyman",
"email":"dan31@example.com"
},
...
]

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:

import UsersIndex from './views/UsersIndex';
 
const router = new VueRouter({
mode: 'history',
routes: [
{
path: '/',
name: 'home',
component: Home
},
{
path: '/hello',
name: 'hello',
component: Hello,
},
{
path: '/users',
name: 'users.index',
component: UsersIndex,
},
],
});

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:

<template>
<div class="users">
<div class="loading" v-if="loading">
Loading...
</div>
 
<div v-if="error" class="error">
{{ error }}
</div>
 
<ul v-if="users">
<li v-for="{ name, email } in users">
<strong>Name:</strong> {{ name }},
<strong>Email:</strong> {{ email }}
</li>
</ul>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
loading: false,
users: null,
error: null,
};
},
created() {
this.fetchData();
},
methods: {
fetchData() {
this.error = this.users = null;
this.loading = true;
axios
.get('/api/users')
.then(response => {
console.log(response);
});
}
}
}
</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:

<li v-for="{ name, email } in users">
<strong>Name:</strong> {{ name }},
<strong>Email:</strong> {{ email }}
</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:

<template>
<div>
<h1>Vue Router Demo App</h1>
 
<p>
<router-link :to="{ name: 'home' }">Home</router-link> |
<router-link :to="{ name: 'hello' }">Hello World</router-link> |
<router-link :to="{ name: 'users.index' }">Users</router-link>
</p>
 
<div class="container">
<router-view></router-view>
</div>
</div>
</template>
<script>
export default {}
</script>

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

fetchData() {
this.error = this.users = null;
this.loading = true;
axios
.get('/api/users')
.then(response => {
this.loading = false;
this.users = response.data;
});
}

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:

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

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:

fetchData() {
this.error = this.users = null;
this.loading = true;
axios
.get('/api/users')
.then(response => {
this.loading = false;
this.users = response.data;
}).catch(error => {
this.loading = false;
this.error = error.response.data.message || error.message;
});
}

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:

<div v-if="error" class="error">
<p>{{ error }}</p>
 
<p>
<button @click.prevent="fetchData">
Try Again
</button>
</p>
</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!

Paul Redmond photo

Staff writer at Laravel News. Full stack web developer and author.

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

Laravel Forge logo

Laravel Forge

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Forge
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
No Compromises logo

No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project. ⬧ Flat rate of $7500/mo. ⬧ No lengthy sales process. ⬧ No contracts. ⬧ 100% money back guarantee.

No Compromises
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $2500/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media
Lunar: Laravel E-Commerce logo

Lunar: Laravel E-Commerce

E-Commerce for Laravel. An open-source package that brings the power of modern headless e-commerce functionality to Laravel.

Lunar: Laravel E-Commerce
LaraJobs logo

LaraJobs

The official Laravel job board

LaraJobs
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit
Rector logo

Rector

Your partner for seamless Laravel upgrades, cutting costs, and accelerating innovation for successful companies

Rector
MongoDB logo

MongoDB

Enhance your PHP applications with the powerful integration of MongoDB and Laravel, empowering developers to build applications with ease and efficiency. Support transactional, search, analytics and mobile use cases while using the familiar Eloquent APIs. Discover how MongoDB's flexible, modern database can transform your Laravel applications.

MongoDB

The latest

View all →
The Inertia.js v2 Beta is Here image

The Inertia.js v2 Beta is Here

Read article
Mastering Laravel, No Compromises, and SourceDive with Joel Clermont image

Mastering Laravel, No Compromises, and SourceDive with Joel Clermont

Read article
Now you can install PHP and the Laravel installer with a single command image

Now you can install PHP and the Laravel installer with a single command

Read article
WireSpy is a Sleek New Debug Bar for Laravel Livewire image

WireSpy is a Sleek New Debug Bar for Laravel Livewire

Read article
The Laracon AU schedule is now live image

The Laracon AU schedule is now live

Read article
Supercharge PhpStorm with Laravel Idea image

Supercharge PhpStorm with Laravel Idea

Read article