[Vuejs]-Laravel send user role into every route [using jetstream vuejs]

1👍

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.

Leave a comment