Search code examples
laraveloctobercmsoctobercms-plugins

get user from belongsToMany relationships


I have a service model in October CMS.

In this model, I need to get postman's users (postman is user group) but I am receiving this error:

Trying to get property of non-object

This is my code

public function getPostmanIdOptions()
{

    $groups = UserGroup::where('id','4')->lists('name', 'id');
    $groups->users;

    $list = [' ' => 'choose'] + $groups;
    return $list;
}

Solution

  • At the moment, your lists() function will only return the name and the id of each user group. This is used to return thelselect options for the backend select (I am assuming).

    What you need to do in this case is return the record based on its id which can be done using the find() eloquent method.

    By doing this, the full UserGroup model will be returned, with it's relationships etc.

    You're new code should look something like this:

    ...    
    
    $group = UserGroup::find(4);
    $users = $group->users;
    
    ...
    

    After retrieving the users, you can then using the lists() method if required to:

    $list = $group->users->lists('name', 'id');