Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel - Selecting specific columns on 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. Both models are thus joined with a 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 groups available within the app:

<?php
    $groups = Group::with('users')->all();
?>

This works, however in the JSON response each user contains all fields from the users table (excluding of course those in the $hidden attribute). I would like this relationship to return only a specific set of fields instead of the whole table.

In other relationship types I can easily achieve this with the following statement (assume now that users may belong to only one group):

<?php
    public function users()
    {
        return $this->hasMany('User')->select(['id', 'first_name', 'last_name']);
    }
?>

However the above does not seem to work with many-to-many relationships. I came across this question which apparently refers to the same issue and it looks like this was not possible in Laravel 4.1. The author of the chosen answer, tptcat, provides a link to an issue on Laravel's Github issue tracker, but the link is no longer working and I couldn't figure whether this issue is still open in 4.2.

Has anybody come across this and successfully managed to solve it?

like image 690
cafonso Avatar asked Jun 30 '14 18:06

cafonso


1 Answers

{
   return $this->belongsToMany('User')->select(array('id', 'name'));
}

use this

like image 165
Tharindu Mahesh Avatar answered Oct 13 '22 20:10

Tharindu Mahesh