mleontenko
1 week ago

Filter by attribute from pivot table

Posted 1 week ago by mleontenko

I have the following method in my model that retrieves all the related users and their roles:

public function operators()
{
        return $this->belongsToMany('App\User', 'obrasciOperateriUloge', 'id_obrasca', 'id_operatera')->withPivot('role');        
}

The results look like this:

[
   {
      "id":8,
      "name":"jjozic",
      "firstname":"Jozo",
      "lastname":"Jozi\u0107",
      "email":"[email protected]",
      "email_verified_at":null,
      "admin":false,
      "active":true,
      "phone":"555",
      "created_at":"2020-03-09 11:26:16",
      "updated_at":"2020-03-09 11:26:16",
      "edited_by":null,
      "edited_at":null,
      "pivot":{
         "id_obrasca":43,
         "id_operatera":8,
         "role":"Author"
      }
   },
   ...
]

I want to add an aditional filter in operators() method that returns only the users with role "Author". How can I do this?

Please sign in or create an account to participate in this conversation.