Home > Blockchain >  Laravel | Returning Array In Model Function
Laravel | Returning Array In Model Function

Time:10-05

i have table users and roles for permission. each user can have 2 or more roles.currently i use foreach when i need to access the users role. what i need is, when i logging in, i want create function that returns array data of roles user login. this is my source.

Users.php (model)

<?php
namespace App\Models;
.
.
.
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.blade.php (view)

<?php

$roleUser = [];
foreach(Auth::user()->roles as $role){
    $roleUser[] = $role->id_role;
}
$idMenu = App\Models\Sistem\RoleMenuModel::whereIn('id_role', $roleUser)->pluck('id_menu')->toArray();

?>

@foreach(App\Models\Sistem\MenuModel::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

and what i wanna do is removing the foreach in sidebar.blade.php and just call the method like :

<?php

$idMenu = App\Models\Sistem\RoleMenuModel::whereIn('id_role', Auth::user()->roles_array)->pluck('id_menu')->toArray();

?>

@foreach(App\Models\Sistem\MenuModel::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

thanks in advance :)

CodePudding user response:

You can create an accessor like this in your RoleMenuModel model.

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

this, collect([]) I have used because if there aren't any roles assign to the user yet, then by default roles_array will return an empty array.

This can be called like this:

Auth::user()->roles_array
  • Related