Laravel 12 + Vue.js + JWT Authentication: A Beginner’s Delight
Imagine building an app where:
- Laravel handles backend logic like a maestro 🎻.
- Vue.js crafts silky-smooth frontend interfaces ✨.
- JWT (JSON Web Tokens) secures user sessions with encrypted tokens 🔒.
Together, they create fast, secure, and scalable apps. Let’s build one step-by-step!
🚀 Step 1: Setup Laravel 12
Skip if you have Laravel installed.
# Install Laravel globally (if needed)
composer global require laravel/installer
# Create a new project
laravel new laravel-vue-jwt
cd laravel-vue-jwt
🔑 Step 2: Integrate JWT Authentication
We’ll use the tymon/jwt-auth package.
Install Package
composer require tymon/jwt-auth
Publish Config
php artisan vendor:publish --provider="Tymon\JWTAuth\Providers\LaravelServiceProvider"
Generate JWT Secret Key
php artisan jwt:secret
(This updates your .env with JWT_SECRET)
👤 Step 3: Configure User Model
Update app/Models/User.php:
use Tymon\JWTAuth\Contracts\JWTSubject;
class User extends Authenticatable implements JWTSubject
{
// ... existing code
public function getJWTIdentifier() {
return $this->getKey();
}
public function getJWTCustomClaims() {
return [];
}
}
🔐 Step 4: Create Auth Routes
Add to routes/api.php:
use App\Http\Controllers\AuthController;
Route::post('/login', [AuthController::class, 'login']);
Route::post('/register', [AuthController::class, 'register']);
Route::middleware('auth:api')->post('/logout', [AuthController::class, 'logout']);
🛠️ Step 5: Build AuthController
Run php artisan make:controller AuthController and add:
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Tymon\JWTAuth\Facades\JWTAuth;
class AuthController extends Controller
{
public function register(Request $request) {
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
]);
return response()->json(['user' => $user], 201);
}
public function login(Request $request) {
$credentials = $request->only('email', 'password');
if (!$token = JWTAuth::attempt($credentials)) {
return response()->json(['error' => 'Unauthorized'], 401);
}
return response()->json(['token' => $token]);
}
public function logout() {
auth()->logout();
return response()->json(['message' => 'Logged out']);
}
}
🌐 Step 6: Setup Vue.js Frontend
Install Vue.js and Axios (for API calls):
npm install vue@next vue-loader@next @vitejs/plugin-vue axios
npm install
Configure Vite
Update vite.config.js:
import { defineConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
export default defineConfig({
plugins: [vue()],
});
📦 Step 7: Create Vue Auth Components
Login.vue (resources/js/components/Login.vue)
<template>
<div>
<input v-model="email" placeholder="Email" type="email">
<input v-model="password" placeholder="Password" type="password">
<button @click="login">Login</button>
</div>
</template>
<script>
import axios from 'axios';
export default {
data() {
return {
email: '',
password: ''
};
},
methods: {
async login() {
try {
const response = await axios.post('/api/login', {
email: this.email,
password: this.password
});
localStorage.setItem('jwt_token', response.data.token);
alert('Logged in!');
} catch (error) {
alert('Login failed!');
}
}
}
};
</script>
🔗 Step 8: Protect API Routes
Add JWT middleware to protected routes in routes/api.php:
Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});
🛡️ Step 9: Secure Axios Requests
In your Vue app, attach the token to requests:
// resources/js/app.js
axios.interceptors.request.use(config => {
const token = localStorage.getItem('jwt_token');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
});
🌟 Step 10: Run Your App!
# Start Laravel backend
php artisan serve
# Build frontend assets
npm run dev
Visit http://localhost:8000 and test your login!
🎉 Congratulations!
You’ve built a Laravel 12 + Vue.js app with JWT authentication. Key wins:
- ✅ Stateless JWT auth for scalability.
- ✅ Clean separation between Vue.js frontend & Laravel API.
- ✅ Beginner-friendly implementation.
“Every great app begins with a single token.” – Anonymous Developer
Happy coding! 🚀
Projects to explore next
Source-code projects from the KritiMyantra catalogue. Check each project's details before buying.
Flask Authentication System (Free Version) - Kritim Yantra
🛠 Features✔ Google & GitHub Authentication✔ User Registration & Login✔ Profile/Dashboard Access✔ Secure & Mi...
Flask Blog CMS with Admin Dashboard — Python Source Code
A Flask-based blogging website with a built-in admin dashboard. Manage articles, images, categories, tags and featured p...
Laravel 12 + ReactJS Starter Kit: Add Multi-Language Support (Arabic, English, Spanish) with Blog CRUD
🚀 Installation & Setup Download & Extract Get the ZIP from kritimyantra.com and extract it. Includes preconfigu...
Comments
No comments yet. Be the first to comment.
Sign in to join the discussion.