When encountering "Undefined property: $client" error, try to obtain information.
P粉329425839
P粉329425839 2023-08-26 23:10:36
0
2
421
<p>I'm using Laravel v5.8 and guzzlehttp v7.4 and trying to write this controller to get some information: </p> <pre class="brush:php;toolbar:false;">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); } }</pre> <p>But when I call the <code>getInfo</code> method, I get the following error message: </p> <p><strong>Undefined property: App\Http\Controllers\Tavanmand\AppResultController::$client</strong></p> <p>However the documentation says to call the uri like this. </p> <p>So what’s the problem here? How can I solve this problem? </p>
P粉329425839
P粉329425839

reply all(2)
P粉842215006

Configure $client as a global variable of this class.

Then set the value in the constructor:

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

Happy coding...

P粉621033928

The scope of your $client variable is limited to inside the constructor. If you want to access it elsewhere, you need to assign it to some kind of class attribute;

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');
    //...
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template