Wow, lots of replies! Thanks everyone..
@JarekTkaczyk bit confused as to what you are saying. Are you suggesting a change in how I ask my question? The title is not the best, I did not know how else to phrase it at the time. But I feel that the content of the post(s) explains what I am trying to accomplish, don't know how else to describe it.
The simple questions I am trying to ask my app - "Does this User belong to a Group that has this specific Permission? If not, were they assigned this Permission directly (not belonging to any Groups)?" Basically, I am trying to allow the Admin users to group large volumes of Users together and assign them all the same Permissions without having to fill up my user_privelege pivot table.
@hostianer Thanks, this looks awesome! But unfortunately it does not seem to do what I am looking for. Simply belonging to a Group does not necessarily mean having a certain Permission. So it's more "does the User inherit a Permission through a Role?"
Here is the code that I used in my last Laravel 4.2 app. I want to somehow handle this using plain vanilla Laravel if possible. Note that in this example, "Groups" is "Levels", "Permissions" is "Roles" - it was not the best table layout.
<?php
class checkAccess {
/**
* @var array Array of level IDs associated with a User
*/
private static $levelIDs;
/**
* @var string Role that we are searching for
*/
private static $role;
/**
* Initialize
*
* Initializes the class
*/
/**
* Check Role Access
*
* Checks to see if a user has access to a particular role.
*
* @param string $role The name of the role we are checking for
* @return bool True if the user has access, false if not
*/
public static function check($role) {
$id = Auth::user()->id; // Use the currently logged in user's ID
$user = User::with('Levels')->find($id);
if (count($user->levels) == 0) {
// The user does not belong to any level groups
return false;
}
self::$role = $role;
$levels = $user->levels;
foreach ($levels as $level) {
if ($level->id == 1)
{
// This is an Admin user, we do not need to continue
return true;
}
self::$levelIDs[] = $level->id;
}
return self::checkRoles();
}
/**
* Check Roles
*
* Checks to see if the user is part of a level that includes this Role.
*
* @return bool True if a match is found, otherwise False
*/
private static function checkRoles()
{
$roleListing = array();
$roles = DB::table('level_role')->join('roles', 'level_role.role_id', '=', 'roles.id')->whereIn('level_role.level_id', self::$levelIDs)->select('roles.name')->get();
if (!$roles) {
return false;
}
foreach ($roles as $role) {
$roleListing[] = $role->name;
}
if (in_array(self::$role, $roleListing)) {
return true;
} else {
return false;
}
}
}
This is called like so:
if (checkAccess::check('Schedule Manager')) {
// Continue
}