Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

EricZwart's avatar

Clean up controller(and bracket)?

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:

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

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

0 likes
8 replies
laracoft's avatar

@ericzwart I would do away with curl and totally rely on Http::

$response = Http::withHeaders([
        "Accept-Language" => "en_US",
        'Accept' => 'application/json',
    ])
    ->post('https://domain.com/api/token', [
        'client_id' => '...',
        'grant_type' => '...'
        'username' => '...'
        'password' => '...'
    ]);
$token = json_decode($response->getBody());

Which part of JSON is adding the []?

Can show what you are getting versus what you want?

laracoft's avatar

@ericzwart

It means they API may return of multiple sets of articles. I will use this code to extract the first, i.e. jump through the []

$list = json_decode($str);
$first = $list[0];
EricZwart's avatar

@laracoft

He does not like it. When I dump the $token to the screen it gives:

object(stdClass)#274 (2) { ["error"]=> string(16) "invalid_clientId" ["error_description"]=> string(42) "Client '' is not registered in the system." }

laracoft's avatar
laracoft
Best Answer
Level 27

@ericzwart Is your client ID correct?

I highly doubt the endpoint is expecting forms, but if it was, you need

$response = Http::withHeaders([
        "Accept-Language" => "en_US",
        'Accept' => 'application/json',
    ])
    ->asForm()
    ->post('https://domain.com/api/token', [
        'client_id' => '...',
        'grant_type' => '...'
        'username' => '...'
        'password' => '...'
    ]);
1 like

Please or to participate in this conversation.