Laravel|返回模型函数中的数组



我有表用户和角色的权限。每个用户可以有2个或更多的角色。目前,当我需要访问用户角色时,我使用foreach。我需要的是,当我登录时,我想要一个返回角色用户登录的数组数据的create函数。这是我的消息来源。

Users.php(型号)

<?php
namespace AppModels;
.
.
.
class User extends Authenticatable implements MustVerifyEmail
{
use HasFactory, Notifiable;
.
.
.
public function roles()
{
return $this->hasMany(RoleUserModel::class, 'id_user');
}
public function roles_array()
{
$roleUser = [];
foreach($this->roles() as $role){
$roleUser[] = $role->id_role;
}
return collect($roleUser);
}
.
.
.
}

sidebar.blad.php(视图)

<?php
$roleUser = [];
foreach(Auth::user()->roles as $role){
$roleUser[] = $role->id_role;
}
$idMenu = AppModelsSistemRoleMenuModel::whereIn('id_role', $roleUser)->pluck('id_menu')->toArray();
?>
@foreach(AppModelsSistemMenuModel::where('parent_id', 0)->whereIn('id', $idMenu)->get() as $menu)
<li class="nav-item">
<a href="{{ $menu->url }}" class="nav-link">
<i class="nav-icon {{ $menu->icon }}"></i>
<p>
{{ $menu->deskripsi }}
</p>
</a>
@if(count($menu->avMenuChilds))
@include('_partials.menuChild',['avMenuChilds' => $menu->avMenuChilds])
@endif
</li>
@endforeach

我想做的是删除sidebade.blade.php中的foreach,然后调用这样的方法:

<?php
$idMenu = AppModelsSistemRoleMenuModel::whereIn('id_role', Auth::user()->roles_array)->pluck('id_menu')->toArray();
?>
@foreach(AppModelsSistemMenuModel::where('parent_id', 0)->whereIn('id', $idMenu)->get() as $menu)
<li class="nav-item">
<a href="{{ $menu->url }}" class="nav-link">
<i class="nav-icon {{ $menu->icon }}"></i>
<p>
{{ $menu->deskripsi }}
</p>
</a>
@if(count($menu->avMenuChilds))
@include('_partials.menuChild',['avMenuChilds' => $menu->avMenuChilds])
@endif
</li>
@endforeach

提前感谢:)

您可以在RoleMenuModel模型中创建这样的访问器。

public function getRolesArrayAttribute(){
return $this->roles()->pluck('id_menu')->toArray() ?? collect([]);
}

我使用了collect([]),因为如果还没有为用户分配任何角色,那么默认情况下roles_larray将返回一个空数组。

这可以这样称呼:

Auth::user()->roles_array

最新更新