Search code examples
laravelvue.jssidebarinertiajslaravel-breeze

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

  • 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
             })
          }
       }
    }