Home > Net >  Check user permissions in vue js laravel
Check user permissions in vue js laravel

Time:01-05

I have a Laravel & Vue project, in my middleware I have:

public function handle($request, Closure $next)
{
    $user = auth()->user();
        
    if ($user->hasRole('admin')) {
        return $next($request);
    } else {
        if ($user->hasRole('staff')) {
            return redirect()->route(get_default_route_by_user($user));
        }
    
    ...

And in my Blade files I use below code and it works perfectly:

@if($service->visible_to_public == '1')
    // Do something
@elseif (auth()->user()->hasRole('admin'))
    // Do something else

How could I, in my Vue files, use the same if conditions as in my Blade files? I tried the below code but It is not working. I am absolutely new to Javascript.

<div v-if="service.visible_to_public == 1">
  Do something
</div>
    
<div v-else-if="(auth()->user()->hasRole('admin'))">
  do something else
</div>

CodePudding user response:

you need to rewrite your functions in JS and get the user details from the api, backend (PHP) and frontend (Vue.js) are completely independant.

An example :

1/ get logged user details, roles, permissions... with GET "/auth/me", store this in your app (vue store, local storage...)

2/ write a function to test if the user has a specific role

function hasRole(user, role) {
  if(!user || !user.role)
    return false

  if(user.role === 'super-admin')
    return true

  return role === user.role
}

You can do the same with permissions :

function hasPermission(user, permission) {
  if(!user || !user.permissions)
    return false

  if(user.role === 'super-admin')
    return true

  if(Array.isArray(permission))
    return user.permissions.some(i => permission.includes(i))
  else
    return user.permissions.includes(permission)
}
  • Related