How to handle session management in Laravel with Vue.js



Image not found!!

Session management in Laravel can be integrated with Vue.js to create a seamless user experience. Laravel provides a robust session management system, and you can use Vue.js to handle the front-end interactions. Here's a step-by-step guide:

1. Set Up Laravel Backend:

Install Laravel Sanctum (if not already installed):

bash
composer require laravel/sanctum

Publish the Sanctum configuration and run migrations:

bash
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider" php artisan migrate

Add middleware to App\Http\Kernel.php:

php
'api' => [ \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class, 'throttle:api', \Illuminate\Routing\Middleware\SubstituteBindings::class, ],

Configure config/cors.php:

php
'paths' => ['api/*'], 'allowed_methods' => ['*'], 'allowed_origins' => ['*'], 'allowed_origins_patterns' => [], 'allowed_headers' => ['*'], 'exposed_headers' => [], 'max_age' => 0, 'supports_credentials' => true,

Set the SESSION_DOMAIN in your .env file:

env
SESSION_DOMAIN=localhost

Set up routes in routes/web.php:

php
use App\Http\Controllers\HomeController; Route::get('/', [HomeController::class, 'index'])->name('home');

Create a controller (e.g., HomeController.php):

bash
php artisan make:controller HomeController
php
// HomeController.php namespace App\Http\Controllers; use Illuminate\Http\Request; class HomeController extends Controller { public function index() { return view('home'); } }

2. Set Up Vue.js Frontend:

Install Vue.js and Axios:

bash
npm install vue axios

Create a Vue component:

vue
<!-- resources/js/components/ExampleComponent.vue --> <template> <div> <h1>Hello, {{ username }}</h1> <button @click="logout">Logout</button> </div> </template> <script> export default { data() { return { username: '', }; }, methods: { async getUser() { try { const response = await axios.get('/api/user'); this.username = response.data.name; } catch (error) { console.error(error); } }, async logout() { try { await axios.post('/logout'); window.location.href = '/'; } catch (error) { console.error(error); } }, }, mounted() { this.getUser(); }, }; </script>

Include the component in your main Vue file:

js
// resources/js/app.js import Vue from 'vue'; import ExampleComponent from './components/ExampleComponent.vue'; new Vue({ el: '#app', components: { ExampleComponent, }, });

Update your Blade view file (e.g., resources/views/home.blade.php):

php
<!-- resources/views/home.blade.php --> <!DOCTYPE html> <html lang="{{ str_replace('_', '-', app()->getLocale()) }}"> <head> <!-- ... --> </head> <body> <div id="app"> <example-component></example-component> </div> <script src="{{ mix('js/app.js') }}"></script> </body> </html>

3. Protect Routes with Middleware:

Apply the auth:sanctum middleware to your routes:

php
// routes/web.php or routes/api.php Route::middleware(['auth:sanctum'])->group(function () { Route::get('/user', function (Request $request) { return $request->user(); }); });

4. Run Your Application:

bash
php artisan serve

Now, your Laravel application is serving on http://localhost:8000, and your Vue.js application is integrated into the Laravel Blade view. When users log in, their session will be managed by Laravel Sanctum, and you can use Vue.js to fetch and display user information.