How to get user role in Yii2? - php

How to get user role in Yii2?
I searched and read Yii2 guide but I didn't find any solution.

You can get Roles for an user by using getRolesByUser function
You can use it like this
\Yii::$app->authManager->getRolesByUser($user_id);

You can use:
Yii::$app->authManager->getRolesByUser(Yii::$app->user->getId());

I use :
if (\Yii::$app->authManager-> getAssignment($role,$rule_id))
for filtering user id and role in rbac, More details on Yii2 Documentation

One more example how to get user role:
Yii::$app->getUser()->identity->role;
It works if you have column with name "role" in your user table.

You can use :
$user =[];
$userAssigned = Yii::$app->authManager->getAssignments(user_id);
foreach($userAssigned as $userAssign){
$user[] = $userAssign->roleName;
}

If you're using amnah/yii2-user module, you can use this:
Yii::$app->user->identity->role->name
It will give you the current user role name

The good and more visual decision will be setting constants of all roles.
$userID = $user->getId();
array_keys(Yii::$app->authManager->getRolesByUser($userID))[0] == User::ROLE_NAME

You can get role of the user by using createcommand.
$roleModel = Yii::$app->db
->createCommand("Select * from auth_assignment where user_id='889'")
->queryOne();
echo $roleModel['item_name'];
This will you user's role in auth assignment. Now you can check that if user is admin or editor or member.

Related

Laravel 5.5 - Only Get Admin Users

I am getting a users details in a Laravel 5.5 controller like this...
$user = Auth::user();
But I want to do a check and see if the user has 'user_type' set to 'admin'
I know I can do a further check once I have the users info but is there a way to combine this into the one statement?
Create a method in User model:
public function isAdmin()
{
return $this->user_type === 'admin';
}
Then use it anywhere in your code:
if (auth()->user()->isAdmin())
Or just do it manually each time:
if (auth()->check() && auth()->user()->user_type === 'admin')
You can even create a global helper and do this:
#if (isAdmin())
This way you can retrieve the user_type of the authenticated user:
$user = Auth::user()->user_type;
As you can see here, the default migration for users does not have a user_type. Hence, if you want to give users certain privileges, you'll have to create it first.
I recommand using a out-of-the-box package. You can (for example) use the package laravel permissions and roles (by Spatie) to do the work for you.

assign roles using moodle core api functions

I'm creating a block in moodle to assign specific system roles to a user. Not sure the best way to do this..
I know you can assign roles from Site administration > User > Permissions > Assign System roles but my block needs to do other things in custom tables.. I have done the part which creates the record in custom tables but this system role is the only item left..and not sure how to do this
could someone please direct me to how I can do this (assign system roles using moodle core api (functions))
or if its a good idea to add record in the role_assignments table.. manually using database queries? and will it work?
$context = context_system::instance();
role_assign($roleid, $userid, $context->id);
Don't directly update the DB table, as that won't trigger event handlers for the role change (or clear relevant caches, etc.).
You can make that method in your plugin, that event will be trigger on role assign to user, for a specific course.
public static function my_plugin_role_assigned(core\event\role_assigned $enrolment_data){
global $DB;
//strange var name, better change it
$enrolment_data_data = $enrolment_data->get_data();
$snapshotid = $enrolment_data->get_data()['other']['id'];
$snapshot = $enrolment_data->get_record_snapshot('role_assignments', $snapshotid);
$roleid = $snapshot->roleid;
$rolename = $DB->get_records_sql("SELECT shortname from {role} WHERE id = ?", array($roleid));
$rolename = array_pop($rolename);
$rolename = $rolename->shortname;
if($rolename == 'editingteacher'){
//My stuff
}
}

Pass the data in the many to many relation ship in laravel

I have create a form that will show the user the event title, event description. And the code
public function show($id){
$showevents = Events::findOrFail($id);
return view('events.show',compact('showevents'));
}
This data i pass dont have the user data, but it will give me the specific event data. My question is how to pass the user data along with this?
Because my event table dont have the user information, it all in the user table.
I try {{$showevents->user->name}} in the view form, but it doesnt give me the information of the user.
You will be needing the user-id too if you want to retrieve infomation about the user and send it to the view file..
One thing you can do for getting the user-id anywhere is setting the user-id in Session variable when the user logs-in as:
\Session::set('user_id',$userID);
Then you can get the user-id anywhere in any controller using
$id = \Session::get('user_id');
For example in your case
public function show($id){
$user_id = \Session::get('user_id');
$user = User::findOrFail($user_id);
$showevents = Events::findOrFail($id);
return view('events.show',compact('showevents','user));
}
Now where you will set the Session variable depends entirely upon your code..I used to set after a user has logged in successfully and also rembember to remove session data when logging out as..
\Session::flush();
First of all {{$showevents->user->name}} of course will fail because you don't have any connection between events and user.
If you want to make connection between it you going to need user_id inside event table.
If you want to get user data but don't have any connection, you need to do in seperate query.
$user = User::findOrFail($user_id);
return view('events.show',compact('showevents', 'user'));
You should use Eloquent's relationship functions or wrap them inside you Models relationship functions and use them.
check the Laravel documentation

Retrieving all users of a specific permission in Laravel 5 / Entrust

How can I retrieve the users of a specific permission in Entrust for Laravel 5.0.
use App\Role;
use App\Permission;
$permission = Permission::find(1);
$roles = $permission->roles;
$users = $roles->users;
I know the code doesn't work... Just an example.
try this
$users = User::permission('edit articles')->get(); // Returns only users with the permission 'edit articles'
I've never used Entrust before, but I looked through the code on GitHub.
Permission has a belongsToMany for roles.
Role has a belongsToMany for users.
Therefore you should be able to chain the commands like so:
$permission = Permission::find(1);
$users = $permission->roles()->users;
If you are planning on chaining relationships, you should add braces onto the relationship name.
Thanks to ntzm, I was able to figure out how to find all the users who have access to the Permission. Not sure if this will help anyone.
There are two different types of employees who has access to a permission. One from the roles and second is where the permission is given direction to them. I haven't used the direct one yet, but I do have roles that have access to permissions. Here's how I was able to get the users with a certain permission:
$permission = Permission::findByName('edit posts');
$employees = [];
//Loop through each role.
foreach($permission->roles as $r){
$emps = $r->users;
//Cycle through the users.
foreach($emps as $e){
$employees[] = $e;
}
}
return $employees;
Hopefully this helped someone who also needed this. :)

Kohana 3.3: WHERE statement with relationships

I have setup Kohana models with relationships define (1:* and : using through) but wanted to know the best way to use them in WHERE statements.
Example: I have a User model and a Post model. Post has a foreign key (userID) to User
I have setup a $_has_many relationship on the User model with an alias user_created
I know I can use the actual field userID, but I want to be able to do something like this
$user->where('user_created', 'IS', NULL);
This would also be handy for checking whether a many-to-many with something like this
'm2m_relation_count', '>', 0
Is this possible? Thanks!
You can do this with the ORM in Kohana in the following way.
$user->user_created->find_all();
This will result in all Posts the User created.
If you want to check if the User has created posts you just use the same function and do a count() on the result and check if it is greater than 0.
I don't think you can use the alias in a where clause itself. You have to call it from the ORM object.
Many-to-many relations work the same way.
1) There is no quick method to get all users without posts. Id prefer to add special column post_count and increment it after posting.
2) You can check user for m:m relationship with has()/has_any() methods:
if ($user->has('roles')) {
// user has at least one role
}
if ($user->has('roles', $roleId) {
// user has role with id=$roleId
}
if ($user->has('roles', array($roleId1, $roleId2))) {
// user has both $roleId and $roleId2 roles
}
if ($user->has_any('roles', array($roleId1, $roleId2))) {
// user has on of the $roleId1 or $roleId2
}

Categories