Home > Blockchain >  Undefined property: $client while trying to get some information
Undefined property: $client while trying to get some information

Time:08-28

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: App\Http\Controllers\Tavanmand\AppResultController::$client

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

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

CodePudding user response:

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');
    //...
}

CodePudding user response:

Make $client as global variable of this class.

then set value at construction like:

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

Happy coding...

  • Related