How to Use Laravel 12 API with Vue.js 3 | asadmukhtar.info
Step-by-Step Guide to Setting Up Authentication in Laravel 12 with Breeze   |   Manual Authentication in Laravel 12: Step-by-Step Guide   |   How to Build a REST API in Laravel 12 with Sanctum   |   Laravel 12 CRUD Application with Image Upload   |   Laravel 12 Multi-Auth System: Admin & User Login   |   How to Integrate Stripe Payment Gateway in Laravel 12   |   Building a Role-Based Access Control (RBAC) in Laravel 12   |   How to Use Laravel 12 Queues and Jobs for Background Tasks   |   Laravel 12 Livewire CRUD Example with Validation   |   Email Verification and Password Reset in Laravel 12   |   How to Use Laravel 12 API with Vue.js 3   |   Laravel 12 AJAX CRUD with jQuery and Bootstrap   |   Laravel 12 Multi-Language Website Setup   |   React Best Practices for 2025: Performance, SEO, and Scalability   |   How to Build a Full-Stack MERN App: A Step-by-Step Guide   |   React State Management: Redux vs. Context API vs. Recoil   |   Server-Side Rendering (SSR) in React with Next.js for SEO   |   How to Optimize React Apps for Faster Load Times   |   Building a REST API with Node.js and Express for a React App   |   Integrating JWT Authentication in React and Node.js (MERN Stack)   |   Real-time Chat App with React, Node.js, and Socket.io   |   How to Deploy a MERN Stack Application on AWS or Vercel   |   Connecting React Frontend to a Node.js Backend with Axios   |   Laravel Implement Flash Messages Example   |   How to integrate Angular 19 with Node.js and Express for full-stack development   |   Best practices for connecting Angular 19 frontend with Laravel API   |   Step-by-step guide to upgrading an existing project to Angular 19   |   How to implement authentication in Angular 19 using JWT and Firebase   |   Optimizing server-side rendering in Angular 19 with route-level render modes   |   Using Angular 19 signals for state management in large applications   |   How to create standalone components in Angular 19 for modular architecture   |   Building a CRUD application in Angular 19 with MongoDB and Express   |   Implementing lazy loading in Angular 19 to improve performance   |   How to integrate Angular 19 with GraphQL for efficient data fetching   |   Vue 3 Composition API vs Options API: A Comprehensive Comparison   |   Fetching and Displaying Data from APIs in Vue.js with Axios   |   Building a Todo App in Vue.js with Local Storage Integration   |   Handling Forms and Validation in Vue.js Using VeeValidate   |   State Management in Vue.js Applications Using Vuex   |   10 Most Important Tasks Every MERN Stack Developer Should Master   |   How to Build a Full-Stack CRUD App with MERN Stack   |   Best Practices for Authentication & Authorization in MERN Stack   |   1. MEAN Stack vs. MERN Stack: Which One Should You Choose in 2025   |   Top 10 Node.js Best Practices for Scalable and Secure Applications   |   How to Build a REST API with Laravel and Node.js (Step-by-Step Guide)   |   Mastering Angular and Express.js for Full-Stack Web Development   |   Top 10 Daily Tasks Every Frontend Developer Should Practice   |   Essential Backend Development Tasks to Boost Your Coding Skills   |   Real-World Mini Projects for Practicing React.js Daily   |   Laravel Developer Task List: Beginner to Advanced Challenges   |   How to Assign Effective Tasks to Your Intern Developers   |   10 Must-Try Tasks to Master JavaScript Fundamentals   |   Practical CSS Challenges That Improve Your UI Design Skills   |   Top Tasks to Learn API Integration in React and Angular   |   Best Task Ideas for a 30-Day Web Development Challenge   |   Top Git and GitHub Tasks Every Developer Should Know   |   30-Day Task Plan for Web Development Interns   |   Weekly Task Schedule for Junior Developers in a Startup   |   How to Track Progress with Development Tasks for Interns   |   What Tasks Should You Give to Interns in a MERN Stack Project   |   Build These 5 Projects to Master React Routing   |   Task-Based Learning: Become a Full-Stack Developer in 90 Days   |   Daily Coding Tasks That Will Sharpen Your Logical Thinking   |   Top 7 Backend Task Ideas to Practice With Node.js and MongoDB   |  

How to Use Laravel 12 API with Vue.js 3

Laravel and Vue.js are a powerful combination for building modern web applications. Laravel 12 is a PHP framework that excels at building robust backends, while Vue.js 3 is a progressive JavaScript framework that allows you to build interactive, dynamic front-end applications.

In this tutorial, we will show you how to use Laravel 12 to create an API backend and then use Vue.js 3 to interact with that API. This setup will allow you to create a full-stack application, where the frontend (Vue.js) interacts with the backend (Laravel API) seamlessly.

Step-by-Step Guide to Using Laravel 12 API with Vue.js 3

Step 1: Install Laravel 12

First, create a new Laravel project if you haven’t already.

composer create-project --prefer-dist laravel/laravel laravel-vue-api

Step 2: Set Up Database and .env File

Configure your database settings in the .env file. For example:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database_name
DB_USERNAME=your_database_username
DB_PASSWORD=your_database_password

Step 3: Set Up API Routes in Laravel

Next, you will need to create the API routes in Laravel. Open routes/api.php and add a simple API route. For example:

use App\Http\Controllers\TaskController;

Route::get('tasks', [TaskController::class, 'index']);
Route::post('tasks', [TaskController::class, 'store']);

Here, we are setting up two routes:

  • GET /tasks: To get a list of tasks.
  • POST /tasks: To create a new task.

Step 4: Create TaskController

Now, let's create a controller that will handle the API requests. Run the following Artisan command to generate the TaskController

php artisan make:controller TaskController

In TaskController.php, implement the index and store methods as follows:

namespace App\Http\Controllers;

use App\Models\Task;
use Illuminate\Http\Request;

class TaskController extends Controller
{
    // Get all tasks
    public function index()
    {
        return Task::all();
    }

    // Store a new task
    public function store(Request $request)
    {
        $task = Task::create([
            'name' => $request->name,
            'description' => $request->description,
        ]);
        return response()->json($task, 201);
    }
}

Make sure the Task model and migration file exist. For this example, a simple tasks table with name and description will suffice.

Run the migration:

php artisan make:model Task -m

In the migration file (database/migrations/xxxx_xx_xx_create_tasks_table.php), define the schema:

public function up()
{
    Schema::create('tasks', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->text('description');
        $table->timestamps();
    });
}

Step 5: Install Vue.js 3

To get started with Vue.js in your Laravel project, you need to install Vue 3.

  1. Install the required NPM packages for Vue.js:
npm install vue@next vue-loader@next @vitejs/plugin-vue

Install Laravel Vite to manage frontend assets. Run:

composer require innologica/laravel-vite

Then, publish the Vite configuration:

php artisan vendor:publish --provider="InnoVait\Vite\ViteServiceProvider"

Install NPM dependencies:

npm install

Step 6: Set Up Vue.js Component

Create a Vue component for managing tasks. Start by creating a new Vue component file.

  1. Create a file at resources/js/components/TaskComponent.vue:
    <template>
      <div>
        <h2>Task List</h2>
        <ul>
          <li v-for="task in tasks" :key="task.id">
            {{ task.name }} - {{ task.description }}
          </li>
        </ul>
        <form @submit.prevent="addTask">
          <input v-model="taskName" placeholder="Task name" required>
          <input v-model="taskDescription" placeholder="Task description" required>
          <button type="submit">Add Task</button>
        </form>
      </div>
    </template>
    
    <script>
    export default {
      data() {
        return {
          tasks: [],
          taskName: '',
          taskDescription: ''
        };
      },
      mounted() {
        this.fetchTasks();
      },
      methods: {
        fetchTasks() {
          fetch('http://localhost/api/tasks')
            .then((response) => response.json())
            .then((data) => {
              this.tasks = data;
            });
        },
        addTask() {
          const task = {
            name: this.taskName,
            description: this.taskDescription,
          };
    
          fetch('http://localhost/api/tasks', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json',
            },
            body: JSON.stringify(task),
          })
            .then((response) => response.json())
            .then((data) => {
              this.tasks.push(data);
              this.taskName = '';
              this.taskDescription = '';
            });
        }
      }
    };
    </script>
    

Step 7: Use Vue Component in Laravel

Now, use the Vue component in the main Laravel view.

  1. Open resources/js/app.js and add the following to import and register the TaskComponent:
import { createApp } from 'vue';
import TaskComponent from './components/TaskComponent.vue';

createApp(TaskComponent).mount('#app');
  1. In resources/views/welcome.blade.php, add the following to mount the Vue component:
<div id="app"></div>
<script src="{{ mix('js/app.js') }}"></script>

Step 8: Compile Assets

Compile your Vue components with the following command:

npm run dev

Now, visit http://localhost and you should see your Vue.js 3 frontend displaying a list of tasks from the Laravel API. You can add tasks through the form, and they will be displayed in real-time.

Conclusion

In this tutorial, we have demonstrated how to set up a Laravel 12 API and connect it to a Vue.js 3 frontend. We used Laravel to build a simple API with CRUD operations and then built a Vue component to interact with the API.

This combination allows you to build modern web applications that have a powerful backend and a dynamic frontend, providing a smooth user experience.


Related Tutorials

Laravel 12 CRUD Application with Image Upload
How to Use Laravel 12 Queues and Jobs for Background Tasks
How to Use Laravel 12 API with Vue.js 3
Laravel 12 AJAX CRUD with jQuery and Bootstrap
Laravel 12 Multi-Language Website Setup
How to Build a REST API with Laravel and Node.js (Step-by-Step Guide)
Laravel Developer Task List: Beginner to Advanced Challenges