Consultation Laravel Eloquent 3 belongtomany tables

Asked

Viewed 89 times

-1

inserir a descrição da imagem aqui1 inserir a descrição da imagem aqui2 inserir a descrição da imagem aqui3

I have 3 tables, Users, Roles and Permissions

Example:

User Carlos has 1 Role Admin and 1 Role Admin has 2 Permissions admin and user

count(Auth::user()
       ->roles()
       ->with('permissions')
       ->whereHas('permissions', function ($q) {
           $q->where('name', 'superadmin');
       })
       ->get()) > 0

here the right query but, if you are going to list all I wanted to hide only who has the permission admin

$user = new User();
$users = $user
      ->roles()
      ->with('permissions')
      ->whereDoesntHave('permissions', function ($q) {
          $q->where('name', 'admin');
      })
      ->get();
  • 1

    Any answers solved your problem? if you can’t add to your questions the entities that compose this filter

2 answers

1


This doubt of yours I’ve had one day I think this is exactly what you want:

$user = User::with('roles', 'roles.permissions')->where('id', auth()->user->id)->first();

dd($user->roles); // retorno de todas as roles
dd($user->roles->permissions); // retorno de todas permissions

0

The way you did it brings the desired result, and finally you do not want what has admin name to include in the query a second parameter, by default when the second parameter is omitted Eloquent understands that you make the comparison by equality

$user = new User();
$users = $user
      ->roles()
      ->with('permissions')
      ->whereDoesntHave('permissions', function ($q) {
          $q->where('name','!=' ,'admin');
      })
      ->get();

Browser other questions tagged

You are not signed in. Login or sign up in order to post.