first commit
This commit is contained in:
63
Traits/HasUsersRelations.php
Normal file
63
Traits/HasUsersRelations.php
Normal file
@ -0,0 +1,63 @@
|
||||
<?php
|
||||
|
||||
namespace Koneko\VuexyStoreManager\Traits;
|
||||
|
||||
use Spatie\Permission\Models\Role;
|
||||
|
||||
trait HasUsersRelations
|
||||
{
|
||||
/**
|
||||
* Relación muchos a muchos entre usuarios y roles en sucursales
|
||||
*/
|
||||
public function storeRoles()
|
||||
{
|
||||
return $this->belongsToMany(Role::class, 'store_user_roles')
|
||||
->withPivot('store_id')
|
||||
->withTimestamps();
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtener el rol de un usuario en una sucursal específica
|
||||
*/
|
||||
public function getRoleForStore($storeId)
|
||||
{
|
||||
return $this->storeRoles()->wherePivot('store_id', $storeId)->first();
|
||||
}
|
||||
|
||||
/**
|
||||
* Verificar si el usuario tiene un rol en una sucursal específica
|
||||
*/
|
||||
public function hasRoleInStore($roleName, $storeId)
|
||||
{
|
||||
return $this->storeRoles()
|
||||
->wherePivot('store_id', $storeId)
|
||||
->where('name', $roleName)
|
||||
->exists();
|
||||
}
|
||||
|
||||
/**
|
||||
* Asignar un rol a un usuario en una sucursal específica
|
||||
*/
|
||||
public function assignRoleToStore($roleId, $storeId)
|
||||
{
|
||||
// Verificar si ya tiene el rol en la sucursal
|
||||
if (!$this->hasRoleInStore($roleId, $storeId)) {
|
||||
return $this->storeRoles()->attach($roleId, ['store_id' => $storeId]);
|
||||
}
|
||||
|
||||
return false; // No hacer nada si ya tiene el rol
|
||||
}
|
||||
|
||||
/**
|
||||
* Remover un rol de un usuario en una sucursal específica
|
||||
*/
|
||||
public function removeRoleFromStore($roleId, $storeId)
|
||||
{
|
||||
// Verificar si realmente tiene el rol antes de eliminarlo
|
||||
if ($this->hasRoleInStore($roleId, $storeId)) {
|
||||
return $this->storeRoles()->detach($roleId, ['store_id' => $storeId]);
|
||||
}
|
||||
|
||||
return false; // No hacer nada si no tiene el rol
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user