How to use "hasPermissionTo" in Vue template

Viewed 29

I am stuck at my code i didnt know how to use hasPermissionTo in vue template to check if role has permission to do something.

<script setup>
import { Link } from "@inertiajs/inertia-vue3"
import { defineProps } from "vue";

const props = defineProps({
    is_admin: Boolean,
    role: Object,
});
</script>

Its Return this:

enter image description here

Now I want to check in in my nav link if role has permission to index that tab?

<Link  class="flex items-center mt-4 py-2 px-6 bg-gray-700 bg-opacity-25 text-gray-100" :href="route('admin.index')" >
    <svg class="h-6 w-6" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"
                    stroke="currentColor">
         <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                        d="M11 3.055A9.001 9.001 0 1020.945 13H11V3.055z" />
         <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                        d="M20.488 9H15V3.512A9.025 9.025 0 0120.488 9z" />
    </svg>
    <span class="mx-3">Dashboard</span>
</Link>

How to check with v-if for if role has permissions to show the dashboard link?

1 Answers

There is different ways to achieve what you want. This is what I'd do:

In HandleInertiaRequests middleware, I'd add the authenticated user roles:

public function share(Request $request)
{
    // I have hardcoded it, but you should get it from db instead (Auth::user()->roles etc)
    return array_merge(parent::share($request), [
        'auth' => [
            'user' => [
                'name' => 'your user name',
                'roles' => [
                    'admin'
                ]
            ]
        ]
    ]);
}

Then, in one of your Vue components, you can check this shared prop (I used Vue3 composition API for the example, adapt it to your version):

<template>
  {{ $page.props.auth.user.roles[0] }}
</template>

or

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

  const userRoles = usePage().props.value.auth.user.roles
</script>
Related