I am trying to use trait because I will put the code in several files as it is an api connection. But when calling the variable that displays the values returned by the api, it is showing undefined in the controller.
App/Http/Traits/UserConnect.php
namespace App\Http\Traits;
use GuzzleHttp\Client;
use GuzzleHttp\RequestOptions;
trait UserConnect
{
public function connectInfo(Request $request)
{
try {
$client = new \GuzzleHttp\Client();
$url = "api_url";
$response = $client->request('GET', $url, [
'headers' => [
'Authorization' => 'Bearer '.$token,
],
]);
$result = json_decode($response->getBody());
return $result;
}catch (\Exception $e){
dd($e);
}
}
}
Controller
<?php
namespace App\Http\Controllers;
use App\Http\Traits\UserConnect;
class HomeController extends Controller
{
use UserConnect;
public function page(Request $request)
{
$api = $this->connectInfo($result);
dd($api);
}
$result is returning undefined but $ api is forcing 1 variable.
$resultwhile you just have$request$api = $this->connectInfo($request);