Home > Software engineering >  Laravel multiauth security check
Laravel multiauth security check

Time:11-21

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

CodePudding user response:

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']);

CodePudding user response:

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 
Spatie\Permission\Traits\HasRoles 
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
  • Related