How to use Vue.js with Laravel

Updated: January 18, 2024 By: Guest Contributor Post a comment

Overview

Vue.js and Laravel are two robust frameworks for front-end and back-end development, respectively. Using them together allows for a seamless development process when building dynamic single-page applications and user interfaces. This tutorial will guide you through integrating Vue.js into a Laravel project.

Prerequisites

Before you start, make sure you have the following installed:

  • PHP (^7.3 or ^8.0) and Composer
  • Node.js and npm
  • Laravel installer

Step-by-Step Instructions

Step 1: Create a New Laravel Project

Begin by creating a new Laravel project. Run the following command:

laravel new my-vue-app

Then, navigate to your project directory:

cd my-vue-app

Step 2: Install Vue

Within your Laravel app, install Vue via npm:

npm install vue

Step 3: Set Up Vue in Laravel

Laravel Mix provides a clean, fluent API for defining Webpack build steps for your application. To integrate Vue, find and update the webpack.mix.js file:

mix.js('resources/js/app.js', 'public/js').vue()

Step 4: Create the Vue Component

In the resources/js/components directory, create a new Vue component called ExampleComponent.vue:

<template>
  <div>
    <h1>{{ message }}</h1>
  </div>
</template>

<script>
export default {
  data() {
    return {
      message: 'Hello Vue! Welcome to Laravel.'
    }
  }
}
</script>

Step 5: Include Vue Components in Your Blade Template

In your main Blade file (e.g., resources/views/welcome.blade.php), include the Vue component:

<div id="app">
  <example-component></example-component>
</div>

<script src="{{ mix('js/app.js') }}"></script>

Step 6: Compile the Assets

Run the following command to compile your assets, which includes your Vue components:

npm run dev

Step 7: Install Laravel’s Official Vue.js Scaffolding

(Optional) With Laravel, you can also use its official scaffolding for Vue.js:

composer require laravel/ui
php artisan ui vue
php artisan ui vue --auth

Conclusion

Vue.js and Laravel are now working together in your project. You have created a new Laravel project, installed Vue, added components, and integrated them with Blade templates. This combination allows for crafting a modern, reactive user interface while benefiting from Laravel’s powerful back-end capabilities.