skip to Main Content

Hey I want to send user role(using Spatie) as props with backend in every route to show different views based on role and permissions in Vuejs.

<!-- Navigation Links -->
<div v-if="user.role == 'admin'" class="hidden space-x-8 sm:-my-px sm:ml-10 sm:flex max-w-xl md:max-w-7xl flex-wrap justify-around">
<NavLink :href="route('dashboard')" :active="route().current('dashboard')">
                                    Dashboard
</NavLink>
</div>

even if could send user role in every route by a middleware or something like that would be good.

do you have any idea?

2

Answers


  1. Chosen as BEST ANSWER

    I used https://inertiajs.com/shared-data.

    
        /**
         * Defines the props that are shared by default.
         *
         * @see https://inertiajs.com/shared-data
         * @param  IlluminateHttpRequest  $request
         * @return array
         */
        public function share(Request $request): array
        {
            return array_merge(parent::share($request), [
                'isAdmin' => auth()->user()->hasRole('admin')
            ]);
        }
    
    <!-- Navigation Links -->
    <div v-if="$page.props.isAdmin" class="hidden space-x-8 sm:-my-px sm:ml-10 sm:flex max-w-xl md:max-w-7xl flex-wrap justify-around">
    <NavLink :href="route('dashboard')" :active="route().current('dashboard')">
                                        Dashboard
    </NavLink>
    </div>
    

  2. Considering you’ve already created the required relations so i’m shooting this one in the dark.
    Lets say you created the roles and associated them with users, you can get the user roles with something like this:

    Route::middleware('auth:api')->group(function () {
        Route::get('/user', function (Request $request) {
            $user = $request->user();
            $role = $user->roles()->first(); // Assuming your user has a "roles" relationship
            return response()->json(['user' => $user, 'role' => $role->name])->header('X-User-Role', $role->name);
        });
    });
    

    Once that’s done then in your ajax call or vue router to intercept the request and then check the user roles to render vue js components based on the required role. You can do something like this in your vuejs :

    // Vue router/index.js

    import Router from 'vue-router'
    
    Vue.use(Router)
    
    const router = new Router({
      // ...
    })
    
    router.beforeEach((to, from, next) => {
      const userRole = localStorage.getItem('userRole') || null // Retrieve the user's role from local storage or set it to null
      const xhr = new XMLHttpRequest()
      xhr.open('GET', '/api/user')
      xhr.setRequestHeader('Authorization', `Bearer ${localStorage.getItem('token')}`)
      xhr.onload = () => {
        if (xhr.status === 200) {
          const response = JSON.parse(xhr.responseText)
          localStorage.setItem('userRole', response.role) // Store the user's role in local storage
          next(vm => {
            vm.$options.propsData.userRole = response.role // Attach the user's role as a prop to the current route
          })
        } else {
          next()
        }
      }
      xhr.send()
    })
    

    This way you can easily render the required pages based on the roles. You can easily modify it according to your requirement it’s not accurate but this can give you an idea how to implement it.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search