laravelhttp-token-authenticationlaravel-controller

Executing function before every controller request


I'm calling cloud APIs using token authentication with php-openstack-sdk.

$openstack = new OpenStack\OpenStack([
    'authUrl' => '{authUrl}',
    'region' => '{region}',
    'user' => [
        'id' => '{userId}',
        'password' => '{password}'
    ],
    'scope' => ['project' => ['id' => '{projectId}']]
]);

However, every API call requires me to be authenticated (as shown in the code above). Instead of repeating the same auth code in every controller function, how do I do it once and be able to call $openstack in my controller's functions? i.e., in my controller, I can directly use $openstack.

public function listServers() 
{
    $openstack->computeV2()->listServers();
}

Solution

  • Write the logic in the __construct() of your Controller.php if you want that to be accessible for all the controllers. If not, write the __construct() within the controller you need.

    Controller.php

    class Controller extends BaseController
    {
        protected $openstack;
    
        public function __construct()
        {
            $this->openstack = new OpenStack\OpenStack([
                ...
            ]);
        }
    }
    

    NetworkController.php

    class NetworkController extends Controller
    {
        public function getNetworkDetails() {
            $network = $this->openstack->networking();
        }
    }