Hi, I'm using a third party API with token auth.
I'm "converting" the code to Laravel.
The Controller shows met the json output.
2 Questions:
-
All works well but I feel the code is not "using" the full use of Laravel maybe the login to get a token should be in a helper?
Does anyone have a suggestion to clean it up or is it fine?
-
The json output creates a file with starting [ and ending bracket ] How can I remove that?
code:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Cache;
class PostdataController extends Controller
{
public function __construct()
{
}
public function index()
{
$postdata = Cache::remember('postcache', 60, function ()
{
$token = '';
// LOGIN
$tokenURL = 'https://domain.com/api/token';
$fields = array(
'client_id'=>'Admin',
'grant_type'=>'password',
'username'=>'[email protected]',
'password'=>'***',
);
$post = http_build_query($fields,'','&');
$ch = curl_init ($tokenURL);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$str = curl_exec($ch);
curl_close ($ch);
// GET TOKEN
$token = json_decode($str);
//print_r($token);
$this->bearer = $token->token_type . ' ' . $token->access_token;
$response = Http::withHeaders(['Accept: application/json','Authorization: '.$this->bearer,])
->get('https://domain.com/api/reports/article/?id=bla');
return json_decode($response);
});
return $postdata;
}
}
Thanks.