Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 4.1 remove pivot attributes from response

Tags:

laravel-4

I am using laravel 4.1 to build an api. I have pivot a table which is working fine. But the response comes with pivot attributes which i don't want. as you will see in my example i have to two tables name: trips and users. I don't want to see pivot table attributes in my response. Here is the example:

[
    {
        "id": 140,
        "name_first": "hasan",
        "name_last": "hasibul",
        "profile_image": "/assets/images/default-profile-img.png",
        "created_at": "2013-09-18 08:19:50",
        "last_login": "2013-12-26 11:28:44",
        "status": "active",
        "last_update": "2013-10-15 13:40:47",
        "google_refresh_token": null,
        "is_admin": 1,
        "updated_at": null,
        "pivot": {
            "trip_id": 200,
            "user_id": 140
        }
    }

This is my User Model:

public function trips(){
        return $this->belongsToMany('Trip');
    }

This is my trip model:

public function users(){
        return $this->belongsToMany('User');
    }

This is my controller:

public function index($tripId)
    {
        $userCollection = Trip::find($tripId)->users;
        return $userCollection;
    }

This is my route:

//get all the users belongs to the trip
Route::get('trips/{tripId}/users', array(
    'as' => 'trips/users/index',
    'uses' => 'TripUserController@index'
));

is there any way i can remove pivot attributes using laravel or i have to use php ?

like image 835
hasib32 Avatar asked Jan 02 '14 16:01

hasib32


1 Answers

Use the $hidden property of the model, you can add attributes or relations to it and the pivot is basicly acts as a relation.

class Foo extends Eloquent
{
    protected $hidden = array('pivot');

    public function bars()
    {
        return $this->belongsToMany('Bar');
    }
}
like image 75
TLGreg Avatar answered Nov 25 '22 14:11

TLGreg