Laravel SPA: A Effortless Guide to Building Single Page Applications (6 Steps)

Laravel SPA: A Complete Guide to Building Single Page Applications

Topics: Laravel, Vue.js, Single Page Application (SPA), Laravel Sanctum, Web Development, JavaScript Frameworks, Frontend Development, Full Stack Development


Introduction

This guide covers building a Single Page Application (SPA) with Laravel and Vue.js. It walks through backend setup, API creation with Sanctum, front-end integration with Vue.js, routing with Vue Router, and data handling with Axios. By following this guide, you can create a seamless, modern web application with a dynamic front-end and a robust Laravel backend.


Part 1: Setting Up Laravel Backend

Step 1: Install Laravel

Install a new Laravel project via Composer:

composer create-project --prefer-dist laravel/laravel spa-demo

Navigate to the project directory:

cd spa-demo

Start the development server:

php artisan serve

Step 2: Install Sanctum for API Authentication

Laravel Sanctum is ideal for SPA authentication.

composer require laravel/sanctum

Publish Sanctum configuration:

php artisan vendor:publish --provider="LaravelSanctumSanctumServiceProvider"
php artisan migrate

Update app/Http/Kernel.php:

protected $middlewareGroups = [
    'web' => [
        ...
        LaravelSanctumHttpMiddlewareEnsureFrontendRequestsAreStateful::class,
    ],
    ...
];

Part 2: Setting Up Vue.js Frontend

Step 1: Install Frontend Dependencies

Install Vue.js and related dependencies using npm:

npm install vue vue-router

Set up vite.config.js:

import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';

export default defineConfig({
    plugins: [vue()],
    resolve: {
        alias: {
            '@': '/resources/js',
        },
    },
});

Update package.json to include Vite scripts:

"scripts": {
    "dev": "vite",
    "build": "vite build"
}

Step 2: Configure Vue.js in Laravel

Create a Vue.js entry file at resources/js/app.js:

import { createApp } from 'vue';
import App from './App.vue';
import router from './router';

createApp(App).use(router).mount('#app');

Create a root Vue component at resources/js/App.vue:

<template>
  <div id="app">
    <router-view />
  </div>
</template>

<script>
export default {
  name: 'App',
};
</script>

<style>
/* Add your styles here */
</style>

Part 3: Vue Router Integration

Step 1: Create a Router

Set up routing in resources/js/router/index.js:

import { createRouter, createWebHistory } from 'vue-router';

const routes = [
    {
        path: '/',
        name: 'home',
        component: () => import('../components/Home.vue'),
    },
    {
        path: '/about',
        name: 'about',
        component: () => import('../components/About.vue'),
    },
];

const router = createRouter({
    history: createWebHistory(),
    routes,
});

export default router;

Step 2: Create Example Components

Create Home.vue:

<template>
  <div>
    <h1>Home Page</h1>
    <p>Welcome to our SPA!</p>
  </div>
</template>

<script>
export default {
  name: 'Home',
};
</script>

Create About.vue:

<template>
  <div>
    <h1>About Page</h1>
    <p>Learn more about this application.</p>
  </div>
</template>

<script>
export default {
  name: 'About',
};
</script>

Part 4: Laravel API Routes and Controller

Step 1: Define API Routes

Update routes/api.php:

use AppHttpControllersAPIUserController;

Route::get('/user', [UserController::class, 'index']);

Step 2: Create Controller

Run the following command:

php artisan make:controller API/UserController

Update UserController.php:

namespace AppHttpControllersAPI;

use AppHttpControllersController;
use IlluminateHttpRequest;

class UserController extends Controller
{
    public function index()
    {
        return response()->json([
            'name' => 'John Doe',
            'email' => 'john.doe@example.com',
        ]);
    }
}

Part 5: Fetching Data with Vue.js

Step 1: Use Axios for API Requests

Install Axios:

npm install axios

Update resources/js/App.vue to fetch user data:

<template>
  <div id="app">
    <router-view />
    <div v-if="user">
      <h3>User Data:</h3>
      <p>Name: {{ user.name }}</p>
      <p>Email: {{ user.email }}</p>
    </div>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'App',
  data() {
    return {
      user: null,
    };
  },
  mounted() {
    axios.get('/api/user')
      .then(response => {
        this.user = response.data;
      })
      .catch(error => console.error(error));
  },
};
</script>

Part 6: Building the Laravel SPA

Step 1: Run Frontend

Compile assets using Vite:

npm run dev

Step 2: Open the Laravel SPA

Navigate to http://localhost:8000 and interact with the app.


Bonus: Authentication with Sanctum

To add authentication:

  1. Set up Sanctum with API tokens.
  2. Create login and registration routes.
  3. Use Axios to send requests and handle token storage.

Conclusion

By following this guide, you’ve built a powerful Laravel SPA leveraging Vue.js, Vue Router, and Sanctum. This application architecture ensures scalability, smooth user interactions, and modern web standards. Continue exploring advanced features like state management with Vuex, server-side rendering, or API optimization to further enhance your SPA development skills.


Dofollow Links

Stay Connected!

  • Connect with me on LinkedIn to discuss ideas or projects.
  • Check out my Portfolio for exciting projects.
  • Give my GitHub repositories a star ⭐ on GitHub if you find them useful!

Your support and feedback mean a lot! 😊

If you need any support regarding your website

If you like our blog, Please support us to improve

Buy Me a Coffee

Leave a Reply

Your email address will not be published. Required fields are marked *

RECENT POST
Leetcode Solutions

633. Sum of Square Numbers

Sum of Square Numbers Difficulty: Medium Topics: Math, Two Pointers, Binary Search Given a non-negative integer c, decide whether there’re

Leetcode Solutions

624. Maximum Distance in Arrays

Maximum Distance in Arrays Difficulty: Medium Topics: Array, Greedy You are given m arrays, where each array is sorted in

Leetcode Solutions

592. Fraction Addition and Subtraction

Fraction Addition and Subtraction Difficulty: Medium Topics: Math, String, Simulation Given a string expression representing an expression of fraction addition