Vue 3 SPA Authentication Session Laravel Scaffolding
This template should help get you started developing with Vue 3 in Vite. The template uses Vue 3 <script setup>
SFCs, check out the script setup docs to learn more.
Recommended IDE Setup
- VS Code + Volar (and disable Vetur) + TypeScript Vue Plugin (Volar).
Clone the frontend project
git clone https://github.com/renatokira/vue-spa-laravel-authentication-session.git
cd vue-spa-laravel-authentication-session
Install dependencies and run
npm install
npm run dev
Screenshots
Laravel Project
If not exist create laravel project
composer create-project laravel/laravel example-app
cd example-app
Database configuration in .env file
Ex Mysql:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=
Or Sqlite:
touch database/database.sqlite
DB_CONNECTION=sqlite
# DB_HOST=127.0.0.1
# DB_PORT=3306
# DB_DATABASE=laravel
# DB_USERNAME=root
# DB_PASSWORD=
Laravel Sanctum
Laravel Sanctum provides a featherweight authentication system for SPAs and simple APIs. (Laravel Sanctum Git). Documentation for Sanctum can be found on the Laravel website.
Install Laravel Breeze
composer require laravel/breeze --dev
php artisan breeze:install api
Migrate to database
php artisan migrate
Configuration in env to define the URLs and domains that can access sessions and authentication cookies created by Laravel
FRONTEND_URL=http://localhost:3000
SANCTUM_STATEFUL_DOMAINS=localhost:3000
SESSION_DOMAIN=localhost
Create test user to login frontend application
php artisan tinker
\App\Models\User::factory()->create([ 'name' => 'Test User', 'email' => 'test@example.com']);
Add in api routes(routes/api.php) to be used in frontend application laravel project:
Route::middleware(['auth:sanctum'])->get('/user', function (Request $request) {
return $request->user();
});
Route::post('/user/edit', function (Request $request) {
$request->validate([
'name' => 'required|min:2|max:255',
]);
try {
$user = $request->user();
$user->name = $request->get('name');
$user->save();
return response()->json(['status' => 'Successful!']);
} catch (\Throwable) {
throw \Illuminate\Validation\ValidationException::withMessages([
'name' => ['unexpected error'],
]);
}
})->middleware(['auth:sanctum']);
Run project
php artisan serve