Building a Vue SPA with Laravel Part 4


February 19th, 2019

Building a Vue SPA with Laravel Part 4

We left off building a real users endpoint and learned about a new way to fetch component data with Vue router in part 3. Now we’re ready to move our attention to creating CRUD functionality for our users—this tutorial will focus on editing existing users.

Along with working through our first form, we will get a chance to look at defining a dynamic Vue route. The dynamic part of our route will be the user’s ID which matches his or her database record. For editing a user, the Vue route will look like this:


The dynamic part of this route is the :id parameter, which will depend on the user’s ID. We are going to use the id field from the database, but you could also use a UUID or something else.

The Setup

Before we focus on the Vue component, we need to define a new API endpoint to fetch an individual user, and then later we’ll need to specify another endpoint to perform the update.

Open the routes/api.php routes file and add the following route below the index route that fetches all users:

1Route::namespace('Api')->group(function () {
2 Route::get('/users', 'UsersController@index');
3 Route::get('/users/{user}', 'UsersController@show');

Using Laravel’s implicit route model binding, our controller method is straightforward. Add the following method to the app/Http/Controllers/Api/UsersController.php file:

1// app/Http/Controllers/Api/UsersController
3public function show(User $user)
5 return new UserResource($user);

Requesting a user at something like /api/users/1 will return the following JSON response:

2 "data": {
3 "name": "Antonetta Zemlak",
4 "email":""
5 }

Our UserResource from Part 3 needs updated to include the id column, so you should update the app/Http/Resources/UserResource.php file to include the id array key. I’ll paste the entire file from Part 3 here:

3namespace App\Http\Resources;
5use Illuminate\Http\Resources\Json\Resource;
7class UserResource extends Resource
9 /**
10 * Transform the resource into an array.
11 *
12 * @param \Illuminate\Http\Request $request
13 * @return array
14 */
15 public function toArray($request)
16 {
17 return [
18 'id' => $this->id,
19 'name' => $this->name,
20 'email' => $this->email,
21 ];
22 }

Now our /api/users and /api/users/{user} routes will respond with the id field, which we need to identify the users in our routes.

Defining the UsersEdit Vue Component

With the show route in place, we can turn our attention to defining the frontend Vue route and the accompanying component. Add the following route definition to the resources/js/app.js routes. Here’s a snippet of importing the UsersEdit component—which we have yet to create—along with the entire route instance:

1import UsersEdit from './views/UsersEdit';
3// ...
5const router = new VueRouter({
6 mode: 'history',
7 routes: [
8 {
9 path: '/',
10 name: 'home',
11 component: Home
12 },
13 {
14 path: '/hello',
15 name: 'hello',
16 component: Hello,
17 },
18 {
19 path: '/users',
20 name: 'users.index',
21 component: UsersIndex,
22 },
23 {
24 path: '/users/:id/edit',
25 name: 'users.edit',
26 component: UsersEdit,
27 },
28 ],

We’ve added the users.edit route to the end of the routes configuration.

Next, we need to create the UsersEdit component at resources/assets/js/views/UsersEdit.vue with the following component code:

2 <div>
3 <form @submit.prevent="onSubmit($event)">
4 <div class="form-group">
5 <label for="user_name">Name</label>
6 <input id="user_name" v-model="" />
7 </div>
8 <div class="form-group">
9 <label for="user_email">Email</label>
10 <input id="user_email" type="email" v-model="" />
11 </div>
12 <div class="form-group">
13 <button type="submit">Update</button>
14 </div>
15 </form>
16 </div>
19export default {
20 data() {
21 return {
22 user: {
23 id: null,
24 name: "",
25 email: ""
26 }
27 };
28 },
29 methods: {
30 onSubmit(event) {
31 // @todo form submit event
32 }
33 },
34 created() {
35 // @todo load user details
36 }

Let’s focus on the template portion first: we render a <form> around a closing div because soon we’ll need to conditionally show the form after loading the user’s data.

The <form> tag has a placeholder @submit event, and we’ve defined an onSubmit() method handler that takes an event object. The last thing I’ll mention is the v-model attributes on the <input> elements, which maps to accompanying data.users Object literal. We’ve stubbed out the default values for id, name, and email.

At this point if you load up /users/1/edit you’ll see an empty form rendered:

We intend on editing existing users, so our next step is figuring out how to grab the dynamic :id property from the route and loading the user’s data from the UsersEdit.vue component.

Loading User Details with a Dedicated Client

Before we load the user data in the component, we’re going to go on a side-quest to extract the /api/users resource into a dedicated API module that we can use to query all users, individual users, and update users.

First, we’re going to create a new folder and file to house the API modules for our backend. You can create these files in any way you please. We’ll demonstrate from the command line on a `Nix command line:

1mkdir -p resources/assets/js/api/
2touch resources/assets/js/api/users.js

The users.js component is going to expose some functions we can call to do operations on the /api/users resource. This module is going to be relatively simple, but later can allow you to do any mapping, data manipulation, etc. before or after the API request. This file serves as a repository of reusable API operations:

1import axios from 'axios';
3export default {
4 all() {
5 return axios.get('/api/users');
6 },
7 find(id) {
8 return axios.get(`/api/users/${id}`);
9 },
10 update(id, data) {
11 return axios.put(`/api/users/${id}`, data);
12 },

Now we can use the same module to get all users, as well as find and update individual users:

1// Get all users
2client.all().then((data) => mapData);
4// Find a user

For now, the all() method doesn’t accept any pagination query params, but I’ll leave it up to you to implement pagination and replace what we have on the UsersIndex.vue component with our new all() client function.

Loading the User from the UsersEdit Component

Now that we have a reusable—albeit very basic—API client, we can put it to work to load the user data when the edit page is rendered.

We originally stubbed out a created() function on our component, which is where we’ll request the user’s data now:

1// UsersEdit.vue Component
3import api from '../api/users';
5export default {
6 // ...
7 created() {
8 api.find(this.$ => {
9 this.loaded = true;
10 this.user =;
11 });
12 }

Our created() callback calls the users.js client find() function which returns a promise. In the Promise callback, we set a loaded data property (which we haven’t created yet) and set the this.user data property.

Let’s add the loaded property to our data key and set it to false by default:

1data() {
2 return {
3 loaded: false,
4 user: {
5 id: null,
6 name: "",
7 email: ""
8 }
9 };

Since our component loads up the data inside of created() we’ll show a conditional “loading” message on the component initially:

1<div v-if="! loaded">Loading...</div>
2<form @submit.prevent="onSubmit($event)" v-else>
3<!-- ... -->

At this point if you refresh the page, the component will briefly flash a Loading... message:

And then the user’s data should populate the form:

The API is very quick, so if you want to verify that the condition is working, you can call setTimeout to delay the setting of the this.user data property:

1api.find(this.$ => {
2 setTimeout(() => {
3 this.loaded = true;
4 this.user =;
5 }, 5000);

The above timeout will show the loading message for five seconds and then set the loaded and user data properties.

Updating the User

We’re ready to hook up the onSubmit() event handler and update the user via the PUT /api/users/{user} API endpoint.

First, let’s add the onSubmit() code and then we’ll move to the Laravel backend to make the backend perform the update on the database:

1onSubmit(event) {
2 this.saving = true;
4 api.update(, {
5 name:,
6 email:,
7 }).then((response) => {
8 this.message = 'User updated';
9 setTimeout(() => this.message = null, 2000);
10 this.user =;
11 }).catch(error => {
12 console.log(error)
13 }).then(_ => this.saving = false);

We’ve called the api.update() function with the current user’s ID, and passed the name and email values from the bound form inputs.

We then chain a callback on the Promise object to set the success message and set the updated user data after the API succeeds. After 2000 milliseconds we clear the message which will effectively hide the message in the template.

For now, we are catching any errors and logging them to the console. In the future, we may go back and cover handling errors such as server failure or validation errors, but for now, we’ll skip over this to focus on the success state.

We use this.saving to determine if our component is in the process of updating the user. Our template ensures the submit button is disabled when a save is in progress to avoid double submissions with a bound :disabled property:

1<div class="form-group">
2 <button type="submit" :disabled="saving">Update</button>

Once the API request is finished, the last thing we’re doing here is setting the this.saving to false by chaining on another then() callback after catch. We need to reset this property to false so the component can submit the form again. Our last then() chain uses the _ underscore variable as a convention you’ll find in some languages indicating that there’s an argument here, but we don’t need to use it. You could also define the short arrow function with empty parenthesis:

1.then(() => this.saving = false);

We’ve introduced two new data properties that we need to add to our data() call:

1data() {
2 return {
3 message: null,
4 loaded: false,
5 saving: false,
6 user: {
7 id: null,
8 name: "",
9 email: ""
10 }
11 };

Next, let’s update our <template> to show the message when it’s set:

2 <div>
3 <div v-if="message" class="alert">{{ message }}</div>
4 <div v-if="! loaded">Loading...</div>
5 <form @submit.prevent="onSubmit($event)" v-else>
6 <div class="form-group">
7 <label for="user_name">Name</label>
8 <input id="user_name" v-model="" />
9 </div>
10 <div class="form-group">
11 <label for="user_email">Email</label>
12 <input id="user_email" type="email" v-model="" />
13 </div>
14 <div class="form-group">
15 <button type="submit" :disabled="saving">Update</button>
16 </div>
17 </form>
18 </div>

Finally, let’s add a few styles for the alert message at the bottom of the UsersEdit.vue file:

1<style lang="scss" scoped>
2$red: lighten(red, 30%);
3$darkRed: darken($red, 50%);
4.form-group label {
5 display: block;
7.alert {
8 background: $red;
9 color: $darkRed;
10 padding: 1rem;
11 margin-bottom: 1rem;
12 width: 50%;
13 border: 1px solid $darkRed;
14 border-radius: 5px;

We’ve finished updating our frontend component to handle a submitted form and update the template accordingly after the API request succeeds. We now need to turn our attention back to the API to wire it all up.

Updating Users in the API Backend

We’re ready to connect all the dots by defining an update method on our User resource controller. We are going to define necessary validation on the server side. However, we aren’t going to wire it up on the frontend yet.

First, we will define a new route in the routes/api.php file for a PUT /api/users/{user} request:

1Route::namespace('Api')->group(function () {
2 Route::get('/users', 'UsersController@index');
3 Route::get('/users/{user}', 'UsersController@show');
4 Route::put('/users/{user}', 'UsersController@update');

Next, the UsersController@update method will use the request object to validate the data and return the fields we intend to update. Add the following method to the app/Http/Controllers/Api/UsersController.php file:

1public function update(User $user, Request $request)
3 $data = $request->validate([
4 'name' => 'required',
5 'email' => 'required|email',
6 ]);
8 $user->update($data);
10 return new UserResource($user);

Just like the show() method, we are using the implicit request model binding to load the user from the database. After validating the required fields, we update the user model and return the updated model by creating a new instance of the UserResource class.

A successful request to the backend will return the user’s updated JSON data, which we then, in turn, use to update the this.user property in the Vue component.

2 "data": {
3 "id": 1,
4 "name":"Miguel Boyle",
5 "email":""
6 }

Navigating to the Edit Page

We’ve been requesting the /users/:id/edit page directly, however, we haven’t added it anywhere in the interface. Feel free to try to figure out how to dynamically navigate to the edit page on your own before seeing how I did it.

Here’s how I added the edit link for each user listed on the /users index page in the UsersIndex.vue template we created back in Part 2:

1<ul v-if="users">
2 <li v-for="{ id, name, email } in users">
3 <strong>Name:</strong> {{ name }},
4 <strong>Email:</strong> {{ email }} |
5 <router-link :to="{ name: 'users.edit', params: { id } }">Edit</router-link>
6 </li>

We restructure the user object in our loop to give us the id, name and email properties. We use the <router-link/> component to reference our users.edit named route with the id parameter passed in the params key.

To better visualize the <router-link> properties, here’s the route definition from the app.js file we added earlier:

2 path: '/users/:id/edit',
3 name: 'users.edit',
4 component: UsersEdit,

If you refresh the app or visit the /users endpoint, you’ll see something like the following:

Putting it All Together

If you edit a user now, the backend should save it and respond with a 200 success if all went well. After the PUT request succeeds you should see the following for two seconds:

Here’s the final UsersEdit.vue component in full for your reference:

2 <div>
3 <div v-if="message" class="alert">{{ message }}</div>
4 <div v-if="! loaded">Loading...</div>
5 <form @submit.prevent="onSubmit($event)" v-else>
6 <div class="form-group">
7 <label for="user_name">Name</label>
8 <input id="user_name" v-model="" />
9 </div>
10 <div class="form-group">
11 <label for="user_email">Email</label>
12 <input id="user_email" type="email" v-model="" />
13 </div>
14 <div class="form-group">
15 <button type="submit" :disabled="saving">Update</button>
16 </div>
17 </form>
18 </div>
21import api from '../api/users';
23export default {
24 data() {
25 return {
26 message: null,
27 loaded: false,
28 saving: false,
29 user: {
30 id: null,
31 name: "",
32 email: ""
33 }
34 };
35 },
36 methods: {
37 onSubmit(event) {
38 this.saving = true;
40 api.update(, {
41 name:,
42 email:,
43 }).then((response) => {
44 this.message = 'User updated';
45 setTimeout(() => this.message = null, 10000);
46 this.user =;
47 }).catch(error => {
48 console.log(error)
49 }).then(_ => this.saving = false);
50 }
51 },
52 created() {
53 api.find(this.$ => {
54 setTimeout(() => {
55 this.loaded = true;
56 this.user =;
57 }, 5000);
58 });
59 }
62<style lang="scss" scoped>
63$red: lighten(red, 30%);
64$darkRed: darken($red, 50%);
65.form-group label {
66 display: block;
68.alert {
69 background: $red;
70 color: $darkRed;
71 padding: 1rem;
72 margin-bottom: 1rem;
73 width: 50%;
74 border: 1px solid $darkRed;
75 border-radius: 5px;


After the user update succeeds, we just reset the message after two seconds. Change the behavior to set the message and then redirect the user back to the previous location (i.e., the /users index page).

Second, add a “Back” or “Cancel” button to the bottom of the form that discards the for updates and navigates back to the previous page.

If you are feeling adventurous, display validation errors when the UsersEdit component sends an invalid request to the API. Clear the error messages after successfully submitting the form.

What’s Next

With updating users out of the way, we will move our attention to deleting users. Deleting a user will be helpful to demonstrate programmatically navigating after successful deletion. We will also look at defining a global 404 page now that we have dynamic routing for editing users.

If you’re ready, move on to Part 5.

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.