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:
bashcomposer require laravel/sanctum
bashphp artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
php artisan migrate
App\Http\Kernel.php
:php'api' => [
\Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
config/cors.php
:php'paths' => ['api/*'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => true,
SESSION_DOMAIN
in your .env
file:envSESSION_DOMAIN=localhost
routes/web.php
:phpuse App\Http\Controllers\HomeController;
Route::get('/', [HomeController::class, 'index'])->name('home');
HomeController.php
):bashphp 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');
}
}
bashnpm install vue axios
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>
js// resources/js/app.js
import Vue from 'vue';
import ExampleComponent from './components/ExampleComponent.vue';
new Vue({
el: '#app',
components: {
ExampleComponent,
},
});
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>
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();
});
});
bashphp 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.