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
Table of Contents
ToggleIntroduction
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:
- Set up Sanctum with API tokens.
- Create login and registration routes.
- 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
- GPT-3 PHP Integration: 5 Steps to Master for PHP with OpenAI’s GPT-3 API
- How to Set Up a PHP Development Environment in VS Code with Docker Desktop A Step-by-Step Guide
- Some Essential Coding Practices Every Experienced Developer Recommends
- A Practical Guide to Writing Better Bash Scripts
- php.ini Overview: Boost Performance, Security, and Flexibility
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! 😊