简体   繁体   中英

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

您可以在关系中使用helper函数with例如:

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

The shortest syntax for this will be:

User::with('roles')->find($id);

There's no need to use first() in this case

尝试这个:

$user = User::with('roles')->where('id',  $id)->first();
public function show(User $user) {
        return $user->load('books');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM