Search code examples
laraveleloquentlaravel-7

laravel eloquent - need help coverting a restrictions white list into a black list


I currently have a resources table :

  • Resources table has the columns: id - title- description - path

and a resource_user_role_restrictions table

  • resource_user_role_restrictionstable has the columns: id - resource_id - role_id - viewable

My model contains the following function that checks the resource_user_role_restrictions table and returns all resources whose resource_user_role_restrictions.role_id matches the passed in $userRoleId and if it's viewable column set to 1:

public function scopeResourcesFilter($query, array $filters) {
     $userRoleId = $filters[0];

     $query->whereHas('resourceUserRoleRestrictions', function  ($query) use($userRoleId){
         $query->where('viewable', 1)->where("role_id", $userRoleId );
     });
    }

This function is called in my controller:

$userRoleId = Auth::user()->role_id;

$resources = Resource::resourcesFilter([$userRoleId])->with('country', 'resourceUserRoleRestrictions')->get();

However, this now needs to be converted into a black list whereby the viewable column is removed and any resource on the table is assumed to be restricted and not viewable, thus not returned. I cant figure out how to get it woking. Ideally this function should now return all items from the resources table except those whose resource_user_role_restrictions.user_role matches the passed in $userRoleId.

Any help at all would be greatly appreciated.


Solution

  • looks like whereDoesntHave() is what I needed.

    $query->whereDoesntHave('resourceUserRoleRestrictions', function  ($query) use($userRoleId){
                $query->where("role_id", $userRoleId );
            });