Building a Vue SPA With Laravel Part 6

https://laravel-news.com/building-a-vue-spa-with-laravel-part-6

We are going to finish the last part of basic CRUD: creating new users. You have all the tools you need from the previous topics we’ve covered thus far, so feel free to try to work on creating users and comparing this article to your efforts.

If you need to catch up, we left off in Part 5 with the ability to delete users and how to redirect users after successful deletion. We also looked at extracting our HTTP client to a dedicated module for reuse across the application. As a reminder, this tutorial isn’t focused on permissions; we are using the built-in Laravel users table to demonstrate working with CRUD within the context of a Vue Router project.

Here’s the series outline thus far:

Adding the Create Users Component

First up, we’re going to create and configure the frontend component for creating new users. The UsersCreate.vue component is similar to the UsersEdit.vue component we created in Part 4:

 1<template> 2    <div> 3        <h1>Create a User</h1> 4        <div v-if="message" class="alert">{{ message }}</div> 5        <form @submit.prevent="onSubmit($event)"> 6          <div class="form-group"> 7              <label for="user_name">Name</label> 8              <input id="user_name" v-model="user.name" /> 9          </div>10          <div class="form-group">11              <label for="user_email">Email</label>12              <input id="user_email" type="email" v-model="user.email" />13          </div>14          <div class="form-group">15              <label for="user_password">Password</label>16              <input id="user_password" type="password" v-model="user.password" />17          </div>18          <div class="form-group">19              <button type="submit" :disabled="saving">20                  {{ saving ? 'Creating...' : 'Create' }}21              </button>22          </div>23        </form>24    </div>25</template>26<script>27    import api from '../api/users';2829    export default {30        data() {31            return {32                saving: false,33                message: false,34                user: {35                    name: '',36                    email: '',37                    password: '',38                }39            }40        },41        methods: {42            onSubmit($event) {43                this.saving = true44                this.message = false45            }46        }47    }48</script>49<style lang="scss" scoped>50$red: lighten(red, 30%);51$darkRed: darken($red, 50%);5253.form-group {54    margin-bottom: 1em;55    label {56        display: block;57    }58}59.alert {60    background: $red;61    color: $darkRed;62    padding: 1rem;63    margin-bottom: 1rem;64    width: 50%;65    border: 1px solid $darkRed;66    border-radius: 5px;67}68</style>

We added the form and inputs and stubbed out an onSubmit method. The rest of the component is identical to the UsersEdit component, except for the addition of the password input. A password is required to create a new user. We skipped having a password field when editing a user because typically, you have a specific password change flow that is separate from editing a user.

Note that we could spend some time extracting the form in both the create and edit views to a dedicated component, but we will leave that for another time (or feel free to work on that independently). The only difference is populating the form with existing user data (including user ID) vs. an empty form for creating users.

Configuring the Route

Next, we need to configure the Vue route and link to the page so we can navigate to the user creation screen. Open the resources/assets/js/app.js file and add the following route (and import):

 1import UsersCreate from './views/UsersCreate'; 2 3// ... 4 5const router = new VueRouter({ 6    mode: 'history', 7    routes: [ 8        // ... 9        {10            path: '/users/create',11            name: 'users.create',12            component: UsersCreate,13        },14        { path: '/404', name: '404', component: NotFound },15        { path: '*', redirect: '/404' },16    ],17});

Next, let’s add the link to the new component in the assets/js/views/UsersIndex.vue component:

1<template>2    <div class="users">3        <!-- ... -->4        <div>5            <router-link :to="{ name: 'users.create' }">Add User</router-link>6        </div>7    </div>8</template>

You should now be able to recompile your frontend assets with yarn watch and see the following:

Submitting the Form

At this point, we don’t have a backend route, so submitting the form via the API client will return a 405 Method Not Allowed. Let’s wire up the onSubmit() handler in the UsersCreate component without defining the route, which will allow us to see the error state of submitting the form quickly:

 1methods: { 2    onSubmit($event) { 3        this.saving = true 4        this.message = false 5        api.create(this.user) 6            .then((data) => { 7                console.log(data); 8            }) 9            .catch((e) => {10                this.message = e.response.data.message || 'There was an issue creating the user.';11            })12            .then(() => this.saving = false)13    }14}

Our form logs out the response data at this point, catches errors and then finally toggles saving = false to hide the “saving” state. We attempt to read the message property from the response or provide a default error message.

Next, we need to add the create() method to the API module we import in the component located at resources/assets/js/api/users.js:

1export default {2    // ...3    create(data) {4        return client.post('users', data);5    },6    // ...7};

The form will send a POST request to the UsersController via the client. If you submit the form, you will see an error message with a 405 response error in the console:

Adding the API Endpoint

We are ready to add the API endpoint in Laravel for creating a new user. It will be similar to editing an existing user. However, this response will return a 201 Created status code.

We will start by defining the route for storing a new user via the API:

1// routes/api.php2Route::namespace('Api')->group(function () {3    // ...4    Route::post('/users', 'UsersController@store');5});

Next, open up the app/Http/Controllers/UsersController.php file and add store() method:

 1public function store(Request $request) 2{ 3    $data = $request->validate([ 4        'name' => 'required', 5        'email' => 'required|unique:users', 6        'password' => 'required|min:8', 7    ]); 8 9    return new UserResource(User::create([10        'name' => $data['name'],11        'email' => $data['email'],12        'password' => bcrypt($data['password']),13    ]));14}

When a user is valid, the new user response looks similar to the following when you submit the form:

1{2  "data": {3    "id":51,4    "name":"Paul Redmond",5    "email":"paul@example.com"6  }7}

If you submit invalid data, you will get something similar the following message:

Handing Success

We already handle what happens with a server error or a validation error; let’s finish up by handling a successful user creation. We’ll clear the form and redirect to the user’s edit page:

 1onSubmit($event) { 2    this.saving = true 3    this.message = false 4    api.create(this.user) 5        .then((response) => { 6            this.$router.push({ name: 'users.edit', params: { id: response.data.data.id } }); 7        }) 8        .catch((e) => { 9            this.message = e.response.data.message || 'There was an issue creating the user.';10        })11        .then(() => this.saving = false)12}

Here’s the final UsersCreate.vue component:

 1<template> 2    <div> 3        <h1>Create a User</h1> 4        <div v-if="message" class="alert">{{ message }}</div> 5        <form @submit.prevent="onSubmit($event)"> 6          <div class="form-group"> 7              <label for="user_name">Name</label> 8              <input id="user_name" v-model="user.name" /> 9          </div>10          <div class="form-group">11              <label for="user_email">Email</label>12              <input id="user_email" type="email" v-model="user.email" />13          </div>14          <div class="form-group">15              <label for="user_password">Password</label>16              <input id="user_password" type="password" v-model="user.password" />17          </div>18          <div class="form-group">19              <button type="submit" :disabled="saving">20                  {{ saving ? 'Creating...' : 'Create' }}21              </button>22          </div>23        </form>24    </div>25</template>26<script>27    import api from '../api/users';2829    export default {30        data() {31            return {32                saving: false,33                message: false,34                user: {35                    name: '',36                    email: '',37                    password: '',38                }39            }40        },41        methods: {42            onSubmit($event) {43                this.saving = true44                this.message = false45                api.create(this.user)46                    .then((response) => {47                        this.$router.push({ name: 'users.edit', params: { id: response.data.data.id } });48                    })49                    .catch((e) => {50                        this.message = e.response.data.message || 'There was an issue creating the user.';51                    })52                    .then(() => this.saving = false)53            }54        }55    }56</script>57<style lang="scss" scoped>58$red: lighten(red, 30%);59$darkRed: darken($red, 50%);6061.form-group {62    margin-bottom: 1em;63    label {64        display: block;65    }66}67.alert {68    background: $red;69    color: $darkRed;70    padding: 1rem;71    margin-bottom: 1rem;72    width: 50%;73    border: 1px solid $darkRed;74    border-radius: 5px;75}76</style>

Conclusion

We have a basic working form to create new users that only have basic validation logic. This tutorial walks you through the basics of doing CRUD in Vue.

As homework, you can define a dedicated user form component for rendering a form for creating a new user and editing existing users if you think it’d be valuable reuse. We are okay with the duplication for now but would be good practice for creating reusable components.

I’d also like to emphasize that I stripped out many nice things we could have done, such as using a CSS framework like Bootstrap, etc. I decided to focus on the core aspects of someone that has never worked with Vue Router or building a single page application before. While to some, the tutorial might feel trivial, to beginners, it focuses on some essential concepts that differ from building traditional server-side applications.

Last updated