Transform Laravel Eloquent result

eloquent, laravel

Solution

You can use an attribute accessor for that. Add this to your model:

protected $hidden = ['teams']; // hide teams relation in JSON output
protected $appends = ['team_names']; // add custom attribute to JSON output

public function getTeamNamesAttribute(){
    return $this->teams->lists('name');
}

To change `hidden` and `appends` dynamically you can use the setter methods:

$data = User::with('teams')->find(2);
$data->setHidden(['teams']);

Problem

When I execute this in my Controller ``` $data = User::with('teams')->find(2); return response(['data' => $data]); ``` I get this as result ``` { "id": 2, "country_id": 1, "first_name": "John", "last_name": "Doe", "created_at": "-0001-11-30 00:00:00", "updated_at": "2015-02-02 23:08:21", "full_name": "John Doe", "teams": [ { "id": 1, "name": "Helpdesk medewerker", "description": "" }, { "id": 2, "name": "Retentie", "description": "" } ] } ``` Im not interested in the full `teams` data, but only interested in the `teamNames` of the user. I've done this by adding this ``` $data->each(function($user) { $user->team_names = $user->teams->lists('name'); unset($user->teams); }); ``` I was wondering if this is the correct way of modifying the Eloquent result.

Original source