I have two models in my Laravel 4.2 web application, User and Group . A user can be a member of many groups, and a group can have many members. Thus, both models are connected to the many-to-many relationship:
<?php class User extends Eloquent { public function groups() { return $this->belongsToMany('Group'); } } class Group extends Eloquent { public function users() { return $this->belongsToMany('User'); } } ?>
One of my API resources is /groups , which lists all the groups available in the application:
<?php $groups = Group::with('users')->all(); ?>
This works, however, in the JSON response, each user contains all the fields from the users table (excluding, of course, those specified in the $hidden attribute). I would like this relation to return only a specific set of fields instead of the entire table.
In other types of relationships, I can easily achieve this with the following statement (suppose users can only belong to one group):
<?php public function users() { return $this->hasMany('User')->select(['id', 'first_name', 'last_name']); } ?>
However, the above does not work with many relationships. I came across this question , which seems to be related to the same issue, and it seems like this is not possible in Laravel 4.1. The author of the selected tptcat answer provides a link to the problem in the Laravel Github log, but the link no longer works, and I could not figure out if this problem remains in 4.2.
Has anyone come across this and successfully dealt with this?