Laravel - Select specific columns for many-to-many relationships

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?

+6
source share
2 answers

The all method takes an array of column names as a parameter.

If you look at the source, by default it accepts * (which means everything).

https://github.com/laravel/framework/blob/4.2/src/Illuminate/Database/Eloquent/Model.php#L624-L629

You can pass the desired columns and return results only with the specified columns.

 <?php $groups = Group::with('users')->all(array('first_column', 'third_column')); 
0
source

Use this.

 <?php class User extends Eloquent { public function groups() { return $this->belongsToMany('Group')->select(array('id', 'name')); } } class Group extends Eloquent { public function users() { return $this->belongsToMany('User')->select(array('id', 'name')); } } ?> 
0
source

Source: https://habr.com/ru/post/971553/


All Articles