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.

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
Laravel Idea for PhpStorm logo

Laravel Idea for PhpStorm

Ultimate PhpStorm plugin for Laravel developers, delivering lightning-fast code completion, intelligent navigation, and powerful generation tools to supercharge productivity.

Laravel Idea for PhpStorm
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
Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate logo

Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate

Build your SaaS application in hours. Out-of-the-box multi-tenancy and seamless Stripe integration. Supports subscriptions and one-time purchases, allowing you to focus on building and creating without repetitive setup tasks.

Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate
JetShip - Laravel Starter Kit logo

JetShip - Laravel Starter Kit

A Laravel SaaS Boilerplate and a starter kit built on the TALL stack. It includes authentication, payments, admin panels, and more. Launch scalable apps fast with clean code, seamless deployment, and custom branding.

JetShip - Laravel 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 →
Dynamic Mailer Configuration in Laravel with Mail::build image

Dynamic Mailer Configuration in Laravel with Mail::build

Read article
Asymmetric Property Visibility in PHP 8.4 image

Asymmetric Property Visibility in PHP 8.4

Read article
Access Laravel Pulse Data as a JSON API image

Access Laravel Pulse Data as a JSON API

Read article
Laravel Forge adds Statamic Integration image

Laravel Forge adds Statamic Integration

Read article
Transform Data into Type-safe DTOs with this PHP Package image

Transform Data into Type-safe DTOs with this PHP Package

Read article
PHPxWorld - The resurgence of PHP meet-ups with Chris Morrell image

PHPxWorld - The resurgence of PHP meet-ups with Chris Morrell

Read article