简体   繁体   English

如何将 Laravel Http 响应作为 json 对象而不是数组返回?

[英]How do I return a Laravel Http response as a json object instead of an array?

I am using the the Laravel Http Client to get a collection of users from the Microsoft Graph API.我正在使用 Laravel Http 客户端从 Microsoft Graph API 获取用户集合。 My code as follows is:我的代码如下:

public function index()
    {
        $response = Http::withToken($this->accessToken)
                        ->get('https://graph.microsoft.com/v1.0/users');
        foreach($response['value'] as $user)
        {
            echo $user['displayName'] . '<br/>';
        }
    }

However, I want to be able to access user details as properties such as:但是,我希望能够将用户详细信息作为属性访问,例如:

public function index()
    {
        $response = Http::withToken($this->accessToken)
                        ->get('https://graph.microsoft.com/v1.0/users');
        foreach($response->value as $user)
        {
            echo $user->displayName . '<br/>';
        }
    }

How would I go about this?我该怎么办?

UPDATE更新

public function index()
    {
        $response = Http::withToken($this->accessToken)
                        ->get('https://graph.microsoft.com/v1.0/users')
                        ->throw();
        $users = $response->object();
        foreach($users->value as $user)
        {
            echo $user->displayName . '<br/>';
        }
    }

Try Below Code it's working properly.试试下面的代码它工作正常。

public function index()
{
    $response = Http::withToken($this->accessToken)
                    ->get('https://graph.microsoft.com/v1.0/users');            
    $response = $response->object();
    foreach($response->value as $user)
    {
        echo $user->displayName . '<br/>';
    }
}

OR或者

public function index()
{
    $response = Http::withToken($this->accessToken)
                    ->get('https://graph.microsoft.com/v1.0/users');
    $response = json_decode(json_encode($response->json()));
    foreach($response->value as $user)
    {
        echo $user->displayName . '<br/>';
    }
}

OR或者

public function index()
{
    $response = Http::withToken($this->accessToken)
                    ->get('https://graph.microsoft.com/v1.0/users');
    $response = (object) $response->json();
    foreach($response->value as $user)
    {
        echo $user->displayName . '<br/>';
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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