why addPermission() with array insert all slug true!
haruncpi opened this issue · 8 comments
haruncpi commented
$module='student';
$user=User::find($userId);
$pp=[
'create' => true,
'read' => true,
'update' => false,
'delete' => false
];
$user->addPermission($module, $pp);
This action insert all value as a true at first time but I am passing update=>false and delete=>false
konovalov-nk commented
@haruncpi
Show output of ->getPermissions()
before and after ->addPermission()
statement.
dd('before', $user->getPermissions());
$user->addPermission($module, $pp);
dd('after', $user->getPermissions());
haruncpi commented
I am sending it with ajax request. The output is
before: Array[0]
after: student {create:true,read:true,update:true,delete:true}
But when I send the request 2nd time it works.
konovalov-nk commented
haruncpi commented
Is it working for you? I can't figure out what is happening behind the scene. It is easy for you to say, what is the reason about that. Please help @konovalov-nk
haruncpi commented
I have solved it by making a function @kodeine
/*
* @return boolean
* $userId
* $module is name of module like student,teacher
* $permissions is a assoc array
*/
function assignPermission($userId, $module, $permissions)
{
$permissionString = json_encode($permissions);
$qry = \DB::select('SELECT count(permissions.id) total FROM permissions
LEFT JOIN permission_user
ON permissions.id=permission_user.`permission_id`
WHERE user_id=:user_id AND name=:name', ['user_id' => $userId, 'name' => $module])[0];
//check module permission already exist with $userId
if ($qry->total) {
//now get the module permission record of user
$result = \DB::select('SELECT permissions.id,name,user_id,slug FROM permissions
LEFT JOIN permission_user
ON permissions.id=permission_user.`permission_id`
WHERE user_id=:user_id AND name=:name', ['user_id' => $userId, 'name' => $module])[0];
//var_dump(json_encode($permissions));
$permissionString = json_encode($permissions);
$p = \DB::table('permissions')
->where('id', $result->id)->update(['slug' => $permissionString]);
if ($p) {
return true;
} else {
return false;
}
} else {
//if module of permission not exit with $userId
$pId = \DB::table('permissions')->insertGetId(['name' => $module, 'slug' => $permissionString]);
if ($pId) {
\DB::table('permission_user')->insert(['permission_id' => $pId, 'user_id' => $userId]);
return true;
} else {
return false;
}
}
}
efriandika commented
I got same issue with @haruncpi
efriandika commented
Example:
$user=User::find($userId);
$user->addPermission('setting', [
'edit' => false,
'view' => false
]);
But the result in database is (slug column):
{"create":true,"read":true,"view":true,"update":true,"delete":true}
Expected Value in Slug Column:
{"edit":false,"view":false}