Skip to content
Advertisement

Undefined property: $client while trying to get some information

I’m using Laravel v5.8 and guzzlehttp of v7.4 and tried to write this Controller for getting some information:

    public function __construct()
    {
        $client = new Client(['base_uri' => 'https://jsonplaceholder.typicode.com/']);
    }
    public function getInfo(Request $request)
    {
        try {
            $response = $this->client->request('GET', 'posts');
            
            dd($response->getContents());
        } catch (ClientException $e) {
            dd($e);
        
        }
    }

But now when I call the method getInfo, I get this error message:

Undefined property: AppHttpControllersTavanmandAppResultController::$client

However the docs says calling the uri’s like this.

So what’s going wrong here? How can I solve this issue?

Advertisement

Answer

The scope of your $client variable is limited to inside your constructor. You want to assign it to some sort of class property if you want to access it elsewhere;

private $client;
    
public function __construct()
{
    $this->client = new Client(['base_uri' => 'https://jsonplaceholder.typicode.com/']);
}

public function getInfo(Request $request)
{
    try {
        $response = $this->client->request('GET', 'posts');
    //...
}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement