Building a Vue SPA with Laravel Part 5
Published on by Paul Redmond
We left off in Part 4 with the ability to edit users and learned how to use v-model
to track changes to the view component user
property. Now we’re ready to look at deleting users and how to handle the UI after the delete action succeeds.
Along the way, we’re going to look at building an Axios client instance to enable greater flexibility in how we configure API clients.
Updating the API to Handle Deleting Users
The first thing we are going to work on is defining the API route for deleting an individual user. Thanks to route model binding this is only a couple of lines in the UsersController
:
public function destroy(User $user){ $user->delete(); return response(null, 204);}
Next, define the new route at the bottom of the Api group in the routes/api.php
file:
Route::namespace('Api')->group(function () { Route::get('/users', 'UsersController@index'); Route::get('/users/{user}', 'UsersController@show'); Route::put('/users/{user}', 'UsersController@update'); Route::delete('/users/{user}', 'UsersController@destroy');});
Deleting Users on the Frontend
We’re going to add the delete functionality to our /users/:id/edit
view component, by adding a delete button to the UsersEdit.vue
component under the “Update” button:
<div class="form-group"> <button type="submit" :disabled="saving">Update</button> <button :disabled="saving" @click.prevent="onDelete($event)">Delete</button></div>
We copied the :disabled
attribute from the update button that we can use to prevent an inadvertent update or delete when an action is taking place.
Next, we need to hook up the onDelete()
callback to handle deleting the user:
onDelete() { this.saving = true; api.delete(this.user.id) .then((response) => { console.log(response); });}
We call the delete()
function on our API client and then chain a callback to log out the response object in the console. The update and delete buttons are disabled if click “delete” because we’re setting this.saving = true
—we will come back to this point in a second. If you have the console open, you will see a 204 No Content
response object indicating the deletion worked.
How to React to a Successfully Deleted User
One thing that’s a little different from updating a user is that we don’t have a user in the database once we delete the record. In a traditional web application, we would likely delete the record and then redirect the user back to the list of all users.
We can do this very thing in our SPA by programmatically navigating the user back to the /users
page:
this.$router.push({ name: 'users.index' })
Applying the this.$router.push()
call to our event, the most basic version would look like this:
onDelete() { this.saving = true; api.delete(this.user.id) .then((response) => { this.$router.push({ name: 'users.index' }); });}
If you refresh the application and delete a user, you will notice a brief flash of disabled buttons, and then the browser navigates to the /users
page without any feedback.
We could handle notifying the user with a dedicated toast/notification mechanism. I’ll leave the approach up to you, but here’s a basic idea of what I’m talking about:
onDelete() { this.saving = true; api.delete(this.user.id) .then((response) => { this.message = 'User Deleted'; setTimeout(() => this.$router.push({ name: 'users.index' }), 2000); });}
The above code sets the this.message
data property we set up in Part 4 and waits two seconds before navigating to the /users
index page.
You could also use something like portal-vue or a component in your layout that flashes the message temporarily (or with a mandatory close button) to indicate an action has succeeded (or failed) to give the user some feedback.
Four Oh Four
You might have noticed that if our Vue route matches the pattern /users/:id/edit
, we still might have a 404
response from the API if the user id is not found:
With a server-side Laravel application, we could render a 404.blade.php
from a ModelNotFoundException
easily. A SPA is a little bit different though. The above route is valid, so we need our component to either render the error component instead of or redirect the user to a dedicated 404 route.
We will add a few new routes to the Vue router configuration in resources/assets/js/app.js
with a dedicated 404 view and a catch-all component that redirects routes that don’t match to the 404 route:
{ path: '/404', name: '404', component: NotFound },{ path: '*', redirect: '/404' },
We’ll create a simple NotFound
component at resources/assets/js/views/NotFound.vue
:
<template> <div> <h2>Not Found</h2> <p>Woops! Looks like the page you requested cannot be found.</p> </div></template>
Because we have a catch-all route on the backend in Laravel, that means that the frontend also needs a catch-all route to respond with a 404 page if the path doesn’t match a defined route. Here’s the backend route as a refresher that catches all routes and sends renders the SPA template:
Route::get('/{any}', 'SpaController@index') ->where('any', '.*');
If you enter an invalid URL like /does-not-exist
, you will see something like the following:
The Vue router hits the wildcard route which redirects the browser to /404
.
Our previous example with an invalid user id still isn’t working yet, because technically the route is valid. We need to update the UsersEdit
component to catch failed requests in the create()
callback and send the user to the 404 route:
created() { api.find(this.$route.params.id) .then((response) => { this.loaded = true; this.user = response.data.data; }) .catch((err) => { this.$router.push({ name: '404' }); });}
Now if you make a request directly to a URI like /users/2000/edit
you should see the app redirect to the 404 page instead of hanging on the “Loading…” UI in the UsersEdit
component.
API Client Options
Although our dedicated users.js
HTTP client might be considered overkill in a small application, I think the separation has already served us well as we use the API module in multiple components. I discuss this idea at great length in my article Building Flexible Axios Clients if you want to learn all the details of what a flexible client affords.
Without changing the external API of our client, we can change how the client works under the hood. For example, we can create an Axios client instance with customizable configuration and defaults:
import axios from 'axios'; const client = axios.create({ baseURL: '/api',}); export default { all(params) { return client.get('users', params); }, find(id) { return client.get(`users/${id}`); }, update(id, data) { return client.put(`users/${id}`, data); }, delete(id) { return client.delete(`users/${id}`); },};
Now I can swap out the baseURL with some configuration later if I want to customize the way the entire module works without affecting the methods.
What’s Next
We learned how to delete users and respond to a successful deletion on the frontend via Vue router. We’ve introduced programmatic navigation via the this.$router
property by registering the Vue router with Vue.use(VueRouter)
in our main app.js
file.
Next, we will turn to build the user creation to wrap up learning how to perform basic create, read, update, and delete (CRUD) actions. At this point you should have all the tools you need to complete creating new users on your own, so feel free to try building this functionality before the publication of the next article in this series.
When you’re ready, check out Part 6 – creating new users