T2theC
T2theC

Reputation: 540

Sentry/Sentinel if user is in role

I am trying to run a check to see if the current user is in a certain role with Cartalyst's Sentinel/Sentry package.

I have found Sentinel::inRole('admin') but can't seem to get it to work. I want something like this:

if(Sentinel::getUser()->hasRole('admin'){ // do some stuff }

I've searched and searched for this and can't find an example to work with. Should I be looking more into permissions or something?

Hopefully someone out there can point me in the right direction.

Cheers

Upvotes: 9

Views: 13388

Answers (3)

Alex
Alex

Reputation: 85

I first check if authorized and if so then watch what role

so works

@if(!Sentinel::guest())
   @if(Sentinel::inRole('user'))
      <ul class="nav navbar-nav navbar-right">
         <li><a href="logout">{{trans('master.logout')}}</a></li>
      </ul>
   @endif
@endif

Upvotes: 0

jerney
jerney

Reputation: 2243

Have your User model extend Cartalyst's 'EloquentUser' model. This model has a getRoles() function that will return the roles for that user. Each user also has an inRole( $role ) function that will return true if the user has the role specified in the parameter.

Extention would look like this:

use Cartalyst\Sentinel\Users\EloquentUser;

class User extends EloquentUser implements ... {
    ....
}

In my opinion this is the cleanest way to accomplish what you want.

If you don't want to do that you could check permissions instead and have your permissions configured like a role

$admin = Sentinel::create()

$admin->permissions = [
    'admin' => true,
];

$admin->save();

Then check the user's permissions instead of checking their role

if($admin->hasAccess('admin') { // do some stuff }

Hope this helps.

-Josh E

Upvotes: 2

Suhayb El Wardany
Suhayb El Wardany

Reputation: 146

You can use inRole here, Sentinel::getUser()->inRole('role_slug');. Of course this would only work if a user is logged in.

You might wanna change it to something like this to prevent calling inRole on a non object.


    if ($user = Sentinel::getUser())
    {
        if ($user->inRole('administrator'))
        {
            // Your logic
        }
    }

Hope that helps.

Upvotes: 13

Related Questions