Integrating Laravel Fortify with a Vue 3 SPA (Single Page Application) involves setting up an API-based authentication system since your Vue app will be running separately from your Laravel backend. Here's a step-by-step guide to help you integrate Fortify with your Vue 3 frontend:
-
Install Laravel Fortify: If you haven't already installed Laravel Fortify, you can do so by running the following command:
composer require laravel/fortify -
Publish Fortify's Resources: Publish Fortify's configuration and views using the following command:
php artisan vendor:publish --provider="Laravel\Fortify\FortifyServiceProvider" -
Configure Fortify: In your
config/fortify.php, make sure you have the features you want enabled, such as login, registration, etc. -
Set Up Fortify for SPA: Since you're using an SPA, you'll want to make sure Fortify is set up to work with JSON responses. In your
App\Providers\FortifyServiceProvider, within thebootmethod, you can define the views to return JSON responses when the request expects JSON:use Laravel\Fortify\Fortify; use Illuminate\Http\Request; Fortify::loginView(function (Request $request) { if ($request->wantsJson()) { return response()->json(['message' => 'Unauthorized'], 401); } // return the login view if you have one }); Fortify::registerView(function (Request $request) { if ($request->wantsJson()) { return response()->json(['message' => 'Unauthorized'], 401); } // return the registration view if you have one }); -
Set Up Middleware: Since you're using a Vue SPA, you won't be able to use the
authmiddleware directly on your routes in the same way as a traditional Laravel app. Instead, you'll need to protect your API routes using theauth:sanctummiddleware if you're using Laravel Sanctum for API token authentication.Route::middleware('auth:sanctum')->get('/user', function (Request $request) { return $request->user(); }); -
Configure CORS: Make sure your
config/cors.phpis set up to allow requests from your Vue SPA's domain. -
Set Up Vue Router: In your Vue application, you'll need to set up navigation guards to protect your routes. Use the
beforeEachhook in Vue Router to check if the user is authenticated before allowing access to certain routes.import { createRouter, createWebHistory } from 'vue-router'; const router = createRouter({ history: createWebHistory(), routes: [ // ... your routes here ], }); router.beforeEach((to, from, next) => { // Check if the route requires authentication and if the user is authenticated if (to.matched.some(record => record.meta.requiresAuth) && !store.isAuthenticated) { next('/login'); // redirect to login page } else { next(); // proceed to route } }); export default router; -
Set Up Pinia Store: Use Pinia to manage your authentication state. You can create an
authstore that keeps track of whether the user is logged in or not.import { defineStore } from 'pinia'; export const useAuthStore = defineStore('auth', { state: () => ({ isAuthenticated: false, // ... other auth-related states }), actions: { // ... actions for logging in, logging out, etc. }, }); -
Handle Authentication in Your Vue Components: In your Vue components, you'll use the
authstore to handle login, registration, and user state.import { useAuthStore } from './stores/auth'; const authStore = useAuthStore(); // Example of a login method function login() { // Call your API to log in, then update the store authStore.isAuthenticated = true; } -
API Calls: When making API calls from your Vue app to your Laravel backend, ensure you're sending the necessary credentials (like API tokens) with your requests. If you're using Axios, you can set up defaults for headers, such as the
Authorizationheader with the token.
Remember to run php artisan migrate after setting up Fortify to ensure that any necessary database tables are created.
This is a high-level overview, and you may need to adjust the code to fit your specific application's needs. Make sure to test your authentication flow thoroughly to ensure security.