kair
kair

Reputation: 1056

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();

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

Answers (4)

fallinov
fallinov

Reputation: 181

public function show(User $user) {
        return $user->load('books');
}

Upvotes: 4

Marcin Nabiałek
Marcin Nabiałek

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

Anoxy
Anoxy

Reputation: 953

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

user::find($id)->with('roles')->first()

Upvotes: 11

Abhishek
Abhishek

Reputation: 3967

Try this:

$user = User::with('roles')->where('id',  $id)->first();

Upvotes: 1

Related Questions