Building a Vue SPA With Laravel Part 6

Published on by

Building a Vue SPA With Laravel Part 6 image

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:

<template>
<div>
<h1>Create a User</h1>
<div v-if="message" class="alert">{{ message }}</div>
<form @submit.prevent="onSubmit($event)">
<div class="form-group">
<label for="user_name">Name</label>
<input id="user_name" v-model="user.name" />
</div>
<div class="form-group">
<label for="user_email">Email</label>
<input id="user_email" type="email" v-model="user.email" />
</div>
<div class="form-group">
<label for="user_password">Password</label>
<input id="user_password" type="password" v-model="user.password" />
</div>
<div class="form-group">
<button type="submit" :disabled="saving">
{{ saving ? 'Creating...' : 'Create' }}
</button>
</div>
</form>
</div>
</template>
<script>
import api from '../api/users';
 
export default {
data() {
return {
saving: false,
message: false,
user: {
name: '',
email: '',
password: '',
}
}
},
methods: {
onSubmit($event) {
this.saving = true
this.message = false
}
}
}
</script>
<style lang="scss" scoped>
$red: lighten(red, 30%);
$darkRed: darken($red, 50%);
 
.form-group {
margin-bottom: 1em;
label {
display: block;
}
}
.alert {
background: $red;
color: $darkRed;
padding: 1rem;
margin-bottom: 1rem;
width: 50%;
border: 1px solid $darkRed;
border-radius: 5px;
}
</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):

import UsersCreate from './views/UsersCreate';
 
// ...
 
const router = new VueRouter({
mode: 'history',
routes: [
// ...
{
path: '/users/create',
name: 'users.create',
component: UsersCreate,
},
{ path: '/404', name: '404', component: NotFound },
{ path: '*', redirect: '/404' },
],
});

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

<template>
<div class="users">
<!-- ... -->
<div>
<router-link :to="{ name: 'users.create' }">Add User</router-link>
</div>
</div>
</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:

methods: {
onSubmit($event) {
this.saving = true
this.message = false
api.create(this.user)
.then((data) => {
console.log(data);
})
.catch((e) => {
this.message = e.response.data.message || 'There was an issue creating the user.';
})
.then(() => this.saving = false)
}
}

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:

export default {
// ...
create(data) {
return client.post('users', data);
},
// ...
};

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:

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

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

public function store(Request $request)
{
$data = $request->validate([
'name' => 'required',
'email' => 'required|unique:users',
'password' => 'required|min:8',
]);
 
return new UserResource(User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]));
}

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

{
"data": {
"id":51,
"name":"Paul Redmond",
"email":"paul@example.com"
}
}

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:

onSubmit($event) {
this.saving = true
this.message = false
api.create(this.user)
.then((response) => {
this.$router.push({ name: 'users.edit', params: { id: response.data.data.id } });
})
.catch((e) => {
this.message = e.response.data.message || 'There was an issue creating the user.';
})
.then(() => this.saving = false)
}

Here’s the final UsersCreate.vue component:

<template>
<div>
<h1>Create a User</h1>
<div v-if="message" class="alert">{{ message }}</div>
<form @submit.prevent="onSubmit($event)">
<div class="form-group">
<label for="user_name">Name</label>
<input id="user_name" v-model="user.name" />
</div>
<div class="form-group">
<label for="user_email">Email</label>
<input id="user_email" type="email" v-model="user.email" />
</div>
<div class="form-group">
<label for="user_password">Password</label>
<input id="user_password" type="password" v-model="user.password" />
</div>
<div class="form-group">
<button type="submit" :disabled="saving">
{{ saving ? 'Creating...' : 'Create' }}
</button>
</div>
</form>
</div>
</template>
<script>
import api from '../api/users';
 
export default {
data() {
return {
saving: false,
message: false,
user: {
name: '',
email: '',
password: '',
}
}
},
methods: {
onSubmit($event) {
this.saving = true
this.message = false
api.create(this.user)
.then((response) => {
this.$router.push({ name: 'users.edit', params: { id: response.data.data.id } });
})
.catch((e) => {
this.message = e.response.data.message || 'There was an issue creating the user.';
})
.then(() => this.saving = false)
}
}
}
</script>
<style lang="scss" scoped>
$red: lighten(red, 30%);
$darkRed: darken($red, 50%);
 
.form-group {
margin-bottom: 1em;
label {
display: block;
}
}
.alert {
background: $red;
color: $darkRed;
padding: 1rem;
margin-bottom: 1rem;
width: 50%;
border: 1px solid $darkRed;
border-radius: 5px;
}
</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.

Paul Redmond photo

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

Filed in:
Cube

Laravel Newsletter

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

image
Paragraph

Manage your Laravel app as if it was a CMS – edit any text on any page or in any email without touching Blade or language files.

Visit Paragraph
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

Bespoke software solutions built for your business. We ♥ Laravel

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
Larafast: Laravel SaaS Starter Kit logo

Larafast: Laravel SaaS Starter Kit

Larafast is a Laravel SaaS Starter Kit with ready-to-go features for Payments, Auth, Admin, Blog, SEO, and beautiful themes. Available with Vue and Livewire stacks.

Larafast: Laravel SaaS Starter Kit
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a 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

The latest

View all →
Configuring Laravel With Additional Environment Files image

Configuring Laravel With Additional Environment Files

Read article
Real Time Command Line Monitoring With Laravel Top image

Real Time Command Line Monitoring With Laravel Top

Read article
A New Validation Rule and the Ability to Manually Fail a Command in Laravel 11.8 image

A New Validation Rule and the Ability to Manually Fail a Command in Laravel 11.8

Read article
New Proposed Array Find Functions in PHP 8.4 image

New Proposed Array Find Functions in PHP 8.4

Read article
Laracon AU 2024 tickets are now on sale image

Laracon AU 2024 tickets are now on sale

Read article
Dash UI is a Laravel Blade Component Library Inspired by Shopify Polaris image

Dash UI is a Laravel Blade Component Library Inspired by Shopify Polaris

Read article