Handling user authentication using Laravel Sanctum and Vue.js involves setting up Sanctum on the Laravel backend to issue API tokens and creating a frontend in Vue.js to manage the authentication process. Here's a step-by-step guide:
Set up Laravel Sanctum:
Install Laravel Sanctum by running composer require laravel/sanctum
.
Publish Sanctum configuration by running php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
.
Run migrations to create necessary tables: php artisan migrate
.
Configure Sanctum in config/auth.php
by adding Sanctum's middleware to the api
guard:
php'guards' => [
'api' => [
'driver' => 'sanctum',
'provider' => 'users',
'hash' => false,
],
],
Set up API routes:
Define routes for authentication in routes/api.php
:
phpRoute::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
Route::post('/login', [AuthController::class, 'login']);
Route::post('/register', [AuthController::class, 'register']);
Route::post('/logout', [AuthController::class, 'logout'])->middleware('auth:sanctum');
Create Authentication Controller:
AuthController
using Artisan: php artisan make:controller AuthController
.AuthController
.Set up Vue.js frontend:
Make API Requests from Vue.js:
/login
route to authenticate users./register
route to create new users./logout
route to invalidate the user's token.Handle Authentication State:
Protect Routes:
Implement Authentication Logic:
Handle Token Expiry and Refresh:
Test thoroughly:
By following these steps, you can set up user authentication using Laravel Sanctum and Vue.js, providing a secure and seamless experience for your users.