search

Home  >  Q&A  >  body text

When encountering "Undefined property: $client" error, try to obtain information.

<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粉329425839P粉329425839444 days ago423

reply all(2)I'll reply

  • P粉842215006

    P粉8422150062023-08-27 13:29:24

    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...

    reply
    0
  • P粉621033928

    P粉6210339282023-08-27 10:48:41

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

    reply
    0
  • Cancelreply