skip to Main Content

Im making a platform with different roles with laravel ,
I wanted to ask if the following code its secure to use to define the roles

For example i want to use different paths for admin and user and to show them some specific content based on roles :
Is this a good way to check the roles or i must modify the code :

  @if(auth()->user()->role=='user')
                    You'are user
                    @elseif(auth()->user()->role=='admin')
                    You're admin
                    @endif

I also want the login to be the same page not to change on the url

2

Answers


  1. If you are wondering if is there possibility that admin role content will be visible to user, there isn’t.

    If you have 3+ user roles, I suggest using laravel-permission.
    You can use stuff like $user->hasRole(‘admin’) or $user->hasAnyRole([‘super-admin’, ‘admin’]);

    Login or Signup to reply.
  2. Try this one

    $user = Auth::user();
    if ($user->hasRole('admin')) {
          You'are admin.
    }else if($user->hasRole('user')) {
           You'are user.
    }
    
    or If you are using Laravel Spatie  package then use this
    
     First, add the 
    SpatiePermissionTraitsHasRoles 
    trait to your User model(s):
    then write inside class  
     use HasRoles;
    
     if($user->getRoleNames()[0]=='user'){
     You'are user.
    }
    
    In Blade
       @role('user')
        I am a user!
    @else
        I am not a user ...
    @endrole
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search