When encountering "Undefined property: $client" error, try to obtain information.
P粉329425839
2023-08-26 23:10:36
<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>
Configure
$client
as a global variable of this class.Then set the value in the constructor:
Happy coding...
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;