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

abhishek009's avatar

How to use Google Spreadsheet API in Laravel Commands?

Hi,

I'm trying to run Google spread sheet api in my laravel command. I have added the dependency using composer as instructed in tutorial. But it's saying ,

 [Symfony\Component\Debug\Exception\FatalThrowableError]
  Class 'App\Command\Google_Client' not found

Composer :

"require": {
        "php": ">=5.6.4",
        "google/apiclient": "^2.0",
        "laravel/framework": "5.4.*",
        "laravel/tinker": "~1.0"
    },

I have following code in my Test() method of command file.

Link: https://developers.google.com/sheets/api/quickstart/php

Code :

<?php

namespace App\Command;

class MyClass
{
    public static function Test()
    {
        define('APPLICATION_NAME', 'Google Sheets API PHP Quickstart');
        define('CREDENTIALS_PATH', '~/.credentials/sheets.googleapis.com-php-quickstart.json');
        define('CLIENT_SECRET_PATH', 'client_secret.json');
        // If modifying these scopes, delete your previously saved credentials
        // at ~/.credentials/sheets.googleapis.com-php-quickstart.json
        define('SCOPES', implode(' ', array(
          Google_Service_Sheets::SPREADSHEETS_READONLY)
        ));

        if (php_sapi_name() != 'cli') {
          throw new Exception('This application must be run on the command line.');
        }

        /**
         * Returns an authorized API client.
         * @return Google_Client the authorized client object
         */
        function getClient() {
          $client = new Google_Client();
          $client->setApplicationName(APPLICATION_NAME);
          $client->setScopes(SCOPES);
          $client->setAuthConfig(CLIENT_SECRET_PATH);
          $client->setAccessType('offline');

          // Load previously authorized credentials from a file.
          $credentialsPath = expandHomeDirectory(CREDENTIALS_PATH);
          if (file_exists($credentialsPath)) {
            $accessToken = json_decode(file_get_contents($credentialsPath), true);
          } else {
            // Request authorization from the user.
            $authUrl = $client->createAuthUrl();
            printf("Open the following link in your browser:\n%s\n", $authUrl);
            print 'Enter verification code: ';
            $authCode = trim(fgets(STDIN));

            // Exchange authorization code for an access token.
            $accessToken = $client->fetchAccessTokenWithAuthCode($authCode);

            // Store the credentials to disk.
            if(!file_exists(dirname($credentialsPath))) {
              mkdir(dirname($credentialsPath), 0700, true);
            }
            file_put_contents($credentialsPath, json_encode($accessToken));
            printf("Credentials saved to %s\n", $credentialsPath);
          }
          $client->setAccessToken($accessToken);

          // Refresh the token if it's expired.
          if ($client->isAccessTokenExpired()) {
            $client->fetchAccessTokenWithRefreshToken($client->getRefreshToken());
            file_put_contents($credentialsPath, json_encode($client->getAccessToken()));
          }
          return $client;
        }

        /**
         * Expands the home directory alias '~' to the full path.
         * @param string $path the path to expand.
         * @return string the expanded path.
         */
        function expandHomeDirectory($path) {
          $homeDirectory = getenv('HOME');
          if (empty($homeDirectory)) {
            $homeDirectory = getenv('HOMEDRIVE') . getenv('HOMEPATH');
          }
          return str_replace('~', realpath($homeDirectory), $path);
        }

        // Get the API client and construct the service object.
        $client = getClient();
        $service = new Google_Service_Sheets($client);

        // Prints the names and majors of students in a sample spreadsheet:
        // https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
        $spreadsheetId = '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms';
        $range = 'Class Data!A2:E';
        $response = $service->spreadsheets_values->get($spreadsheetId, $range);
        $values = $response->getValues();

        if (count($values) == 0) {
          print "No data found.\n";
        } else {
          print "Name, Major:\n";
          foreach ($values as $row) {
            // Print columns A and E, which correspond to indices 0 and 4.
            printf("%s, %s\n", $row[0], $row[4]);
          }
        }
    }
}

Do I need to add something else ?

Thanks!

0 likes
6 replies
WebKenth's avatar

Did you remember to dump your autoload file?

composer dump-autoload

LYiub's avatar

Any Answer, Have you got the answer for yr question ?

cometads's avatar

This is over three years old but here's the solution:

Google_Client is in the global namespace so you either need to change the calls to new \Google_Client(); or add use Google_Client;.

Please or to participate in this conversation.