Home > Mobile >  Access Session data in Laravel 9 using Vuejs3 and InertiaJs
Access Session data in Laravel 9 using Vuejs3 and InertiaJs

Time:09-06

I am working on my first Laravel project using Vuejs for the frontend. One of the functions of my app is to allow a Super admin to login as a User(impersonate). When I click the Impersonate Button, impersonate is added to Session so I can access it in the view. This works in my other Laravel/Blade projects.

Pages/Users/Index.vue

...
<Link @click="impersonate(user.id)">Impersonate</Link>
... 
<script>
...
methods: {
    impersonate(id) {
        this.$inertia.post(route("user.impersonate", id));
    },
},
...
</script>

enter image description here

UserController.php

...
public function impersonate(User $user)
{
    /*if(! is_null(auth()->user()->account_id)) {
        return;
    }*/

    $originalId = auth()->user()->id;
    session()->put('impersonate', $originalId);
    auth()->loginUsingId($user->id);

    return redirect('/users');
}
...

Impersonation works and I can successfully login as other Users, but I can't figure out how to access Session data inside Vue so I can show a block with a logout link--with Blade I would simply write:

@if(session()->has('impersonate'))
    ...
        <div>
            You are impersonating {{auth()->user()->name}}
        </div>
        <div>
            <a href="{{route('leave-impersonation')}}">
                Leave Impersonation
            </a>
        </div>
    ...
@endif

How can I write the if part in Vue?

CodePudding user response:

To access that variable in your components, you previously have to share it in HandleInertiaRequests middleware.

For example, here I'm getting logged user's email in the template:

<template>
  {{ $page.props.auth.user.email }}
</template>

If you want to access that prop in the script side you'll have to use usePage.

Example of getting logged user's email in the script section (example made using Vue3 composition API, but you can fit it into your needs):

<script setup>
  import { usePage } from '@inertiajs/inertia-vue3'

  const userEmail = usePage().props.value.auth.user.email
</script>
  • Related