Reputation: 1056
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();
Returns:
{
"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;
Returns:
{
"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
Upvotes: 2
Views: 4299
Reputation: 111829
The shortest syntax for this will be:
User::with('roles')->find($id);
There's no need to use first()
in this case
Upvotes: 2
Reputation: 953
You can in your relationship use the helper function with
like so as:
user::find($id)->with('roles')->first()
Upvotes: 11
Reputation: 3967
Try this:
$user = User::with('roles')->where('id', $id)->first();
Upvotes: 1