MorshedSaif
MorshedSaif

Reputation: 399

returning value from a function in middleware in laravel

i've a function in my admin model which has connected to role model by many to many relationship. i created a middleware to check the roles of admins and redirect them to their dashboard, but i'm not sure it is returning the correct value. here is the way i'm checking -> Auth::check() && Auth::user()->role(). i mean the role() method is returning the role_id but how to check it ? like Auth::check() && Auth::user()->role()->role_id == 1, though this is not a correct way

Upvotes: 1

Views: 168

Answers (2)

Mihir Bhende
Mihir Bhende

Reputation: 9045

You can create a function in your User(or Admin whichever is authenticatable) Model :

<?php 

public function hasRoles(array $roles)
{
    return $this->roles()->whereIn('role_id', [$roles])->exists();
}

// Then you can check using ids
const ADMIN_ROLE = 1;
const OTHER_ROLE = 2;

if(Auth::user() && Auth::user()->hasRoles([self::ADMIN_ROLE, self::OTHER_ROLE])){
// Current user is either admin or other role
}

If you have name of a role then you can use that instead of ids as well.

Upvotes: 1

Giorgi Lagidze
Giorgi Lagidze

Reputation: 831

Here is the better way.

In user model, write a function something like this .

public function hasRole( ... $roles ) {
   foreach ($roles as $role) {
      if ($this->roles->contains('column_name', $role)) {
         return true;
      }
   }
   return false;
}

in middleware, you'd write something like this

if(Auth::user() && Auth::user()->hasRole("admin", "moderator)){
   return $next($request);
}

This way you'd not check for ids , because ids might change.

Upvotes: 0

Related Questions