'Display sidebar menu elements based on user's role, with "yaminncco/vue-sidebar-menu" package
Hi I'm using Laravel Breeze with Inertia JS. I'm using "yaminncco / vue-sidebar-menu package" for the sidebar.
I'm asking if there is a way to display menu element depending on the user role (admin : See everything, simple user not, ....). There is nothing about this in the package doc.
So if any one has an idea Or Can suggest a better way (or package) for building sidebar when working with Laravel Breeze?
Thanks
Solution 1:[1]
If this is something you want to do in all of your pages, you can do this sharing the property via the HandleInertiarRequests
middleware share
method.
public function share(Request $request)
{
return array_merge(parent::share($request), [
'user_role' => Auth::user()->role
]);
}
Now all of your pages will receive this prop at $pages.props.user_role
on your Vue page components. Then you can do:
<template>
<sidebar-menu v-if="user_role === 'admin'" :menu="menu" />
</template>
<script>
export default {
props: {
user_role: String
}
}
</script>
If you're using the sidebar component on a Vue component that is not a page component, for example, in a layout component, you'll have the compute the prop from the $page.props
:
<template>
<sidebar-menu v-if="user_role === 'admin'" :menu="menu" />
</template>
<script>
export default {
computed: {
user_role () {
return this.$page.props.user_role
}
}
}
</script>
If you want to select which menu items the menu should render based on the user_role
you can compute the menu
property:
export default {
data () {
return {
menuItems: [
{
href: '/',
title: 'Dashboard',
icon: 'fa fa-user'
},
{
href: '/charts',
title: 'Charts',
icon: 'fa fa-chart-area',
admin: true
}
]
}
},
computed: {
menu () {
if (this.user_role === 'admin') {
return this.menuItems // return all the items
}
return this.menuItems.filter((item) => {
return !item.admin // return only items NOT marked as admin
})
}
}
}
Solution 2:[2]
You can hide menu items according to your user role (or according to user groups). Make sure that you get menu instance by calling a function because hidden properties must be updated each time. Example:
function getMenu() {
return [
{
header: 'Main Navigation'
},
{
href: '/',
title: 'Dashboard',
hidden: !checkPermission(DashboardPage.groups),
}
{
href: '/configuration',
title: 'Configuration',
hidden: !checkPermission(ConfigurationPage.groups),
}
]
}
const menuComputed = computed(() => {
if(loggedIn.value) {
return getMenu();
}
else {
return menuLoginOnly.value;
}
});
...
<sidebar-menu
class="sidebar"
:menu="menuComputed"/>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Dmitry Vasilyev |