Flyde Flyde - 1 year ago 147
PHP Question

Access eloquent relationships when return object as json

I am currently building a JSON RESTful API with Laravel/Lumen and now trying to access model attributes that are being stored in the relationship of this model

// I also want to return User->roles
return User::find(1)->first();


"id": 2,
"email": '...'

I actually found a way but that seems pretty much hacked and not clean

// Get user
$user = User::find($id)->first();

// Make roles public
$user->roles = $user->roles;

// Return object
return $user;


"id": 2,
"email": '...',
"roles": [

Is there a better way? Or is this kind of a security thing where you want to protect your data? But since you can access the relationship in php why shouldn't it be returned as json object?

Couldn't find something in the laravel documentation


You can in your relationship use the helper function with like so as: