Laravel-将雄辩的对象传播到数组中

时间:2019-11-13 03:54:28

标签: php laravel

考虑以下代码:

tokenArray = [
    $this->me(),
    'access_token' => $token,
    'token_type' => 'bearer',
    'expires_in' => auth()->factory()->getTTL() * 60,
];

和输出:

enter image description here

如何在用户对象中的属性分散在$ tokenArray中?

所需的输出:

enter image description here

2 个答案:

答案 0 :(得分:1)

合并数组。

$tokenArray = $this->me()->toArray() + [
    'access_token' => $token,
    'token_type' => 'bearer',
    'expires_in' => auth()->factory()->getTTL() * 60,
];

Laravel 6.x Docs - Eloquent - Serializing Models and Collections - Serializing to Array toArray

PHP Manual - Operators - Array Operators +

答案 1 :(得分:1)

尝试此代码:

$obj = $this->me(),

$obj是对象变量,您需要更改令牌数组然后获取输出,我认为这是正确的:

tokenArray = [
    'id'  => $obj['0']->id
    'name'  => $obj['0']->name
    'username'  => $obj['0']->username
    'email'  => $obj['0']->email
    'access_token' => $token,
    'token_type' => 'bearer',
    'expires_in' => auth()->factory()->getTTL() * 60,
];

另一种方法:

如果可以使用雄辩的方法:

$obj = $this->me()->get()->toArray()

print_r($obj + $tokenArray);

这对于最佳答案是更好的。