Integrating Vue.js with Laravel: Step-by-Step Guide to Full Stack Development

Umur Alpay
CodeResult
Published in
16 min readMay 23, 2023

This story is originally published at https://coderesult.com/blog/integrating-vue-js-with-laravel-step-by-step-guide-to-full-stack-development/

The world of web development has witnessed a myriad of technologies that have revolutionized the way we create applications. Among these, Laravel and Vue.js have emerged as two powerful tools that, when used in conjunction, can dramatically enhance the developer’s productivity and the application’s performance.

Laravel, an open-source PHP framework, is lauded for its elegance, simplicity, and readability. It provides robust tools and a comprehensive ecosystem that simplifies complex tasks such as routing, security, and caching, thereby allowing developers to focus more on the business logic of the application.

On the other hand, Vue.js, a progressive JavaScript framework, has gained popularity for its adaptability and gentle learning curve. Vue.js excels in building dynamic, single-page applications by offering a simple yet powerful API for managing state, rendering data, and handling user interactions.

But why use Laravel and Vue.js together? The answer is simple: Vue.js’ reactive components offer a more efficient way to build the front-end, which, when coupled with Laravel’s robust and scalable back-end, creates a potent combination for modern full-stack development. This synergy can lead to applications that are not only powerful and scalable, but also maintainable and testable.

In this blog post, we will delve deep into the process of integrating Vue.js with Laravel. We’ll provide a step-by-step guide to setting up your environment, creating Vue components, managing state with Vuex, making API requests with Axios, and more. By the end of this guide, you’ll have a solid foundation for building your own full-stack applications using Laravel and Vue.js.

Whether you’re a seasoned developer looking to expand your skill set, or a novice just starting your journey in full-stack development, this guide aims to equip you with the knowledge you need to confidently integrate Vue.js with Laravel. So, let’s embark on this exciting journey of full-stack development.

Prerequisites

Before we embark on our journey of integrating Vue.js with Laravel, there are a few prerequisites you should be aware of. Familiarity with these concepts and technologies will significantly smooth your path to mastering full-stack development using Laravel and Vue.js.

1. Basic Knowledge of PHP & Laravel: Since Laravel is a PHP framework, a basic understanding of PHP and its object-oriented programming concepts is vital. Familiarity with Laravel, its principles, and its architectural patterns (like MVC) would be highly beneficial, although not mandatory. We’ll be delving into Laravel throughout this guide, so if you’re still new to it, don’t worry!

2. Understanding of JavaScript & Vue.js: Vue.js is a progressive JavaScript framework, so having a grasp on JavaScript fundamentals will be necessary. If you have experience with Vue.js, that’s great. However, beginners are also welcome as we’ll be covering Vue.js fundamentals as well.

3. Familiarity with Web Development Basics: This includes a fundamental understanding of HTML & CSS, familiarity with the command line, and a basic knowledge of web protocols like HTTP/HTTPS and methods like GET and POST.

4. A Local Development Environment: You need a local development environment set up with PHP, Composer (Dependency Manager for PHP), and Node.js installed. Laravel utilizes Composer to manage its dependencies, and Node.js is used for managing JavaScript packages.

5. Text Editor: Any text editor suitable for web development will work, but some popular choices among developers are Visual Studio Code, Sublime Text, or Atom.

6. Laravel DevTools: While not mandatory, tools such as Laravel Mix, Artisan, and Eloquent ORM can drastically improve your development experience.

With these prerequisites out of the way, you are ready to step into the world of full-stack development with Laravel and Vue.js. The next section will guide you through the installation and setup process, paving the way for your first Laravel-Vue project.

Installation and Setup

Once you have a basic understanding of PHP, Laravel, JavaScript, Vue.js, and web development, it’s time to get your hands dirty. In this section, we’ll walk you through the process of installing Laravel and Vue.js and setting up your first Laravel-Vue project.

1. Installing Laravel

The first step is to install Laravel. Assuming you have PHP and Composer installed in your development environment, you can create a new Laravel project using the following command in your terminal:

composer create-project --prefer-dist laravel/laravel blog

This command will create a new Laravel application in a directory named ‘blog’. Feel free to replace ‘blog’ with whatever name suits your project.

2. Laravel UI Installation

Next, we need to install the Laravel UI package. This package provides a simple way to scaffold basic login and registration views using Vue.js as the JavaScript framework. Install it using Composer:

composer require laravel/ui

After installing Laravel UI, you can create the authentication scaffolding with Vue using the following command:

php artisan ui vue --auth

3. Installing Node.js and NPM

Node.js and NPM (Node Package Manager) are necessary for managing JavaScript packages. If not already installed, you can download Node.js and NPM from the official website. Confirm the installation by checking the version of Node.js and NPM using the following commands:

node -v npm -v

4. Installing Vue.js

With Laravel UI, Vue.js is already installed and configured. However, to ensure all dependencies, including Vue.js, are installed, navigate to your Laravel project directory and run:

npm install

5. Compiling Assets

Finally, Laravel Mix can be used to compile your assets. Run the dev command for a one-time compilation of your assets:

npm run dev

You can also use the watch command to automatically compile your assets whenever changes are detected:

npm run watch

And that’s it! With these steps, you’ve successfully installed Laravel and Vue.js, set up the initial scaffolding for authentication, and compiled your assets. You’re now ready to start building with this powerful duo. In the next sections, we’ll explore building Vue components, managing state with Vuex, making API calls with Axios, and more.

Building Your First Vue Component

With the installation and setup complete, it’s time to start building. The first thing we’ll tackle is creating a Vue component. Vue components are reusable Vue instances with a name, and they serve as the building blocks of a Vue application.

1. What are Vue Components?

In essence, Vue components are custom elements that Vue’s compiler attaches behavior to. They are reusable, encapsulating functionality that can be imported into various parts of your application, promoting code reuse and modularity.

2. Creating a Vue Component

Creating a Vue component in Laravel is quite simple. Laravel stores Vue components in the resources/js/components directory by default. Let's create a new Vue component named ExampleComponent.vue.

Navigate to the resources/js/components directory, create a new file and name it ExampleComponent.vue. Inside this file, we'll structure our first Vue component like so:

<template>
<div>
<h1>Hello from ExampleComponent!</h1>
</div>
</template>
<script>
export default {
name: 'ExampleComponent'
}
</script>
<style scoped></style>

The <template> block holds the HTML that will be associated with the component. The <script> block is where you define the component's functionality. Lastly, the <style> block is where you would put any CSS specific to the component.

3. Using Vue Components

To use our newly created ExampleComponent, we must first register it in our app.js file, which is located in the resources/js directory:

Vue.component('example-component', require('./components/ExampleComponent.vue').default);

Now you can use your Vue component in any of your Blade files like so:

<example-component></example-component>

Remember to compile your assets using npm run dev or npm run watch for Laravel Mix to pick up the new component.

4. Passing Data to Vue Components

To make components reusable and dynamic, you often need to pass data from Laravel to Vue. You can achieve this using props. Props are custom attributes you can register on a component, allowing data to be passed from parent components to child components.

For example, let’s pass a title prop to our ExampleComponent:

<example-component title="My First Vue Component"></example-component>

And accept this prop in our Vue component:

<template>
<div>
<h1>{{ title }}</h1>
</div>
</template>
<script>
export default {
name: 'ExampleComponent',
props: ['title']
}
</script>

Now, you’ve created your first Vue component in Laravel, used it in a blade file, and passed data to it. Vue components form the foundation of any Vue.js application, and understanding them is crucial to mastering Vue.js. In the next section, we’ll explore integrating Vue Router with Laravel, which will bring us one step closer to developing robust full-stack applications.

Integrating Vue Router with Laravel

As we move forward with building our full-stack application, managing navigation becomes an essential aspect of the development process. This is where Vue Router comes into play. Vue Router is the official router for Vue.js. It deeply integrates with Vue.js core to make building Single Page Applications (SPAs) with Vue.js a breeze. In this section, we will discuss how to integrate Vue Router with Laravel.

1. Installing Vue Router

The first step is to install Vue Router. While in your project directory, run the following command in your terminal:

npm install vue-router

2. Setting Up Vue Router

After installing Vue Router, it’s time to set it up. In your resources/js directory, create a new file and name it routes.js. This is where you'll define all your Vue routes.

Next, import Vue and Vue Router in this file and tell Vue to use Vue Router. Your routes.js file should look like this:

import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)const router = new VueRouter({
mode: 'history',
routes: [
// your routes go here
]
})
export default router

The mode: 'history' option enables the HTML5 History mode, which removes the hash in the URL and makes the application URL look more like a standard URL.

3. Defining Vue Routes

Now that Vue Router is set up, you can define routes in the routes array. For instance, let's say we want to create a route for our ExampleComponent:

import ExampleComponent from './components/ExampleComponent.vue'
const router = new VueRouter({
mode: 'history',
routes: [
{ path: '/example', component: ExampleComponent }
]
})

With this setup, when you navigate to /example in your application, the ExampleComponent will be rendered.

4. Using Vue Router in Your Application

Finally, you need to use the router in your main Vue instance. In your app.js file, import the router and add it to your Vue instance:

import router from './routes'
const app = new Vue({
el: '#app',
router
});

Now, Vue Router is fully integrated into your Laravel and Vue.js application. You can navigate to different parts of your application using <router-link>:

<router-link to="/example">Go to Example</router-link>

And you can render the components of the current route in your main blade file using <router-view>:

<router-view></router-view>

Integrating Vue Router with Laravel allows you to manage routes in your Vue components, making it easier to build complex SPAs. With Vue Router, you can build a seamless, powerful navigation system in your full-stack application. In the following sections, we will continue to explore other essential aspects of using Vue.js with Laravel, such as state management with Vuex and making API requests with Axios.

State Management with Vuex

As your application grows in complexity, managing state (data) across components can become increasingly difficult. This is where Vuex, the official state management pattern and library for Vue.js, becomes incredibly useful. Vuex provides a centralized store for all the components in an application, ensuring that state can only be mutated in a predictable way. In this section, we’ll look at how to integrate Vuex with our Laravel-Vue setup.

1. Installing Vuex

The first step is to install Vuex. While in your project directory, run the following command in your terminal:

npm install vuex

2. Setting Up Vuex

After installing Vuex, you’ll need to set up your store. In your resources/js directory, create a new file and name it store.js. This is where you'll define your Vuex store.

Next, import Vue and Vuex in this file, and tell Vue to use Vuex. Your store.js file should look like this:

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)export default new Vuex.Store({
state: {
// your state properties go here
},
mutations: {
// your mutation functions go here
},
actions: {
// your action functions go here
},
getters: {
// your getter functions go here
}
})

3. Understanding Vuex Core Concepts

Vuex operates based on the following core concepts:

State: The state object is where you define the data structure of your application’s state.

Getters: Getters are functions that allow components to retrieve state data from the store.

Mutations: Mutations are synchronous functions that are responsible for changing the state in the Vuex store.

Actions: Actions are similar to mutations, but they are responsible for performing asynchronous operations before committing mutations.

Let’s consider a simple example where we have a counter state, which can be incremented:

export default new Vuex.Store({
state: {
counter: 0
},
mutations: {
increment (state) {
state.counter++
}
},
actions: {
increment ({ commit }) {
commit('increment')
}
},
getters: {
counter: state => state.counter
}
})

4. Using Vuex in Your Application

To make the store available to your components, you need to pass it to your root Vue instance. Update your app.js file as follows:

import store from './store'
const app = new Vue({
el: '#app',
router,
store
});

With this setup, you can now use Vuex in your Vue components. For instance, in your ExampleComponent, you can display the counter state, increment it, and watch for changes:

<template>
<div>
<h1>{{ counter }}</h1>
<button @click="increment">Increment</button>
</div>
</template>
<script>
export default {
name: 'ExampleComponent',
computed: {
counter() {
return this.$store.state.counter;
}
},
methods: {
increment() {
this.$store.dispatch('increment');
}
}
}
</script>

With Vuex, you can now manage shared state in your application effectively, making it easier to build complex applications. In the next section, we will explore how to communicate with a server using Axios, completing our full-stack setup.

Making API Requests with Axios

In this final section, we will discuss how to use Axios to make HTTP requests from your Vue.js application to your Laravel API. Axios is a promise-based HTTP client for the browser and Node.js, and it integrates well with Vue.js.

1. Installing Axios

To use Axios, you first need to install it. Run the following command in your terminal:

npm install axios

2. Using Axios to Make HTTP Requests

After installing Axios, you can import it in any Vue component to make HTTP requests. For instance, let’s assume you have a /api/posts endpoint in your Laravel API that returns a list of posts. You can make a GET request to this endpoint as follows:

<template>
<!-- ... -->
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
posts: []
};
},
created() {
axios.get('/api/posts')
.then(response => {
this.posts = response.data;
})
.catch(error => {
console.error(error);
});
}
}
</script>

In this example, the created lifecycle hook is used to fetch the posts when the component is created.

3. Handling CSRF Protection

Laravel comes with CSRF protection out of the box. Therefore, when making POST, PUT, PATCH, or DELETE requests, you need to send the CSRF token along with your request.

Luckily, Laravel automatically adds the CSRF token to a meta tag in your application's head, and Axios can be configured to send it automatically with every request. This is already set up for you in the bootstrap.js file that comes with Laravel:

let token = document.head.querySelector('meta[name="csrf-token"]');
if (token) {
axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
} else {
console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');
}

Form Submission with Vue and Laravel

Form submission is a common task in web applications, allowing users to input data that the application can then process. In this section, we will see how to handle form submission with Vue.js and Laravel.

1. Creating a Form with Vue

The first step in handling form submission is to create a form. We’ll be working in Vue, so we can take advantage of v-model to create two-way data bindings on form input and textarea elements.

Let’s say we have a form where a user can create a new post:

<template>
<form @submit.prevent="submitForm">
<input v-model="form.title" type="text" placeholder="Title">
<textarea v-model="form.body" placeholder="Body"></textarea>
<button type="submit">Submit</button>
</form>
</template>
<script>
export default {
data() {
return {
form: {
title: '',
body: ''
}
};
},
methods: {
submitForm() {
// we'll handle the submission in the next steps
}
}
}
</script>

In this code, we create a form with title and body inputs. The v-model directive creates a two-way data binding between the form inputs and the form data property. The @submit.prevent="submitForm" directive prevents the form from being submitted the traditional way (which would cause a page refresh), and instead calls the submitForm method.

2. Submitting the Form to Laravel with Axios

The next step is to handle the form submission. When the form is submitted, we want to send a POST request to the Laravel API to create a new post. We’ll use Axios to make this request:

<script>
import axios from 'axios';
export default {
// ...
methods: {
submitForm() {
axios.post('/api/posts', this.form)
.then(response => {
// handle success
console.log(response.data);
})
.catch(error => {
// handle error
console.log(error);
});
}
}
}
</script>

In the submitForm method, we're making a POST request to the /api/posts endpoint, sending along the form data. If the request is successful, we log the response data to the console, and if it fails, we log the error.

3. Handling Validation Errors

Often, you’ll want to validate the input data before creating a new post. Laravel makes this easy with its powerful validation features. If the validation fails, Laravel will return a 422 Unprocessable Entity status code along with the validation errors.

We can enhance our submitForm method to handle these validation errors and display them to the user:

<script>
import axios from 'axios';
export default {
data() {
return {
form: {
title: '',
body: ''
},
errors: {}
};
},
methods: {
submitForm() {
axios.post('/api/posts', this.form)
.then(response => {
// handle success
this.form.title = '';
this.form.body = '';
this.errors = {};
console.log(response.data);
})
.catch(error => {
if (error.response.status === 422) {
this.errors = error.response.data.errors;
} else {
console.log(error);
}
});
}
}
}
</script>

Here, we’re adding an errors data property to store the validation errors. If the status code of the error response is 422, we set the errors data property to the errors from the response data.

Testing Vue Components in Laravel

Testing is a critical part of software development that helps ensure your application works as expected and can significantly reduce bugs in production. Vue.js comes with robust testing utilities, and Laravel provides an elegant PHP testing suite. In this section, we’ll focus on how to write tests for Vue components in a Laravel application.

1. Setting up Testing Tools

To test Vue components, we’ll use Vue Test Utils and Jest. Vue Test Utils is the official unit testing utility library for Vue.js, and Jest is a delightful JavaScript Testing Framework with a focus on simplicity.

First, we need to install the necessary dependencies:

npm install --save-dev jest @vue/test-utils vue-jest babel-jest

After installing the dependencies, we need to configure Jest. Create a new file in your root directory named jest.config.js and add the following content:

module.exports = {
moduleFileExtensions: ['js', 'json', 'vue'],
transform: {
'^.+\\.js$': 'babel-jest',
'.*\\.(vue)$': 'vue-jest'
}
};

This configuration tells Jest to transform JavaScript and Vue files using babel-jest and vue-jest, respectively.

2. Writing a Vue Component Test

Let’s consider testing a simple Vue component, ExampleComponent.vue, which includes a button that emits an event when clicked. Here's what the component looks like:

<template>
<button @click="emitEvent">Click me</button>
</template>
<script>
export default {
methods: {
emitEvent() {
this.$emit('clicked');
}
}
}
</script>

We can write a test for this component to check if it emits the ‘clicked’ event when the button is clicked. Create a new file named ExampleComponent.spec.js in a directory named tests under resources/js:

import { shallowMount } from '@vue/test-utils';
import ExampleComponent from '@/components/ExampleComponent.vue';
describe('ExampleComponent.vue', () => {
it('emits clicked event when button is clicked', async () => {
const wrapper = shallowMount(ExampleComponent);
await wrapper.find('button').trigger('click'); expect(wrapper.emitted().clicked).toBeTruthy();
});
});

In this test, we’re using Vue Test Utils to mount the component and simulate a button click, and then we’re using Jest’s expect function to assert that the 'clicked' event was emitted.

3. Running the Tests

Finally, we can run the tests by adding a test script in our package.json file:

"scripts": {
"test": "jest"
}

Now, you can run your tests with the following command:

npm run test

Deploying Laravel & Vue.js Applications

After you’ve developed and tested your Laravel and Vue.js application, the next step is to deploy it to a production server. In this section, we’ll look at a general overview of the steps you might take to deploy your full stack Laravel and Vue.js application.

1. Preparing for Deployment

Before deploying your application, you must prepare it for a production environment. This involves several steps:

  • Set the APP_ENV variable in your .env file to production.
  • Run php artisan config:cache to cache the configuration files. In a production environment, you should always use the configuration cache for performance reasons.
  • Run php artisan route:cache to cache the routes. Just like with configuration caching, route caching can drastically increase the performance of your application.
  • Run npm run production to compile your assets for production. This will minify your JavaScript and CSS files, making them smaller and faster to download.

2. Choosing a Hosting Provider

The next step is to choose a hosting provider. There are many great options out there for Laravel and Vue.js applications, including but not limited to:

  • Laravel Forge: a server management platform created by Taylor Otwell, the creator of Laravel. Forge can provision and manage servers on various cloud hosting providers, including DigitalOcean, Linode, AWS, and others.
  • Vapor: another product from Laravel, Vapor is a serverless deployment platform for Laravel, powered by AWS.
  • Heroku: a cloud platform that can run various types of apps, including PHP and Node.js apps.
  • VPS providers: you can also choose to set up your own server on a VPS provider like DigitalOcean, Linode, or AWS.

3. Deploying the Application

Once your application is prepared for deployment and you’ve chosen a hosting provider, you can deploy your application. The exact process depends on your hosting provider. Generally, it involves:

  • Pushing your code to a Git repository.
  • Pulling the code on the server.
  • Installing dependencies with Composer and npm.
  • Running database migrations with php artisan migrate.
  • Setting up a web server like Nginx or Apache to serve your application.

Conclusion

We’ve journeyed through the process of integrating Vue.js with Laravel, providing you a practical, step-by-step guide for full-stack development. From the installation of necessary tools and building your first Vue component to form handling, testing, and eventually deploying your application — we’ve covered it all.

Laravel and Vue.js are powerful technologies on their own, and when used together, they can create remarkably efficient, scalable, and robust web applications. By using Vue.js as a front-end framework with Laravel as the back-end, we can benefit from the robustness of Laravel and the reactivity of Vue.js.

As with any technological endeavor, practice makes perfect. I encourage you to keep experimenting with Laravel and Vue.js to hone your skills further. Use this guide as a starting point and explore more advanced topics as you grow comfortable with these technologies.

Always remember that the vibrant communities surrounding Laravel and Vue.js are a gold mine of information, and they’re always ready to assist you. Use the wealth of resources available, ask questions, and continue learning.

I hope this guide has provided you with a solid understanding and a good starting point for developing full-stack web applications with Laravel and Vue.js.

Follow me on Instagram, Facebook or Twitter if you like to keep posted about tutorials, tips and experiences from my side.

You can support me from Patreon, Github Sponsors, Ko-fi or Buy me a coffee

--

--