invokable-laravel-google-sheets

repository·main·Indexed 19 days ago

https://github.com/invokable/laravel-google-sheets

A Laravel-idiomatic wrapper for the Google Sheets API v4 providing a fluent interface for reading, writing, and managing spreadsheets with Laravel Collection integration. It supports Service Account, OAuth 2.0, and API Key authentication. The package allows for range updates, appending values, sheet management, and provides a macroable Sheets facade to extend functionality.

Tokens
12.1K
Snippets
53
Records
67
Agent score
66%

What's inside invokable-laravel-google-sheets

  1. Choose the right authentication method

    main

    Depending on your use case, choose one of the following authentication methods:

    • Service Account: Recommended for most Laravel applications, automated systems, and background jobs. It uses a JSON key file to authenticate as a non-human user.
    • OAuth 2.0: Use when your application needs to act on behalf of a specific user to access their personal Google Sheets.
    • API Key: Only suitable for reading public spreadsheets. This is very limited in scope.
  2. When to use OAuth 2.0 authentication

    main

    OAuth 2.0 authentication is the preferred method when your application needs to access a user's personal Google Sheets. Use this method for:

    • User-centric applications: Where users interact with their own spreadsheets.
    • Multi-tenant applications: Where different users access different spreadsheets.
    • Personal data access: Reading or writing data from a user's personal Google account.
    • Desktop or web applications: Where user interaction is available to grant permissions.
  3. Avoid naming conflicts with the sheets() method

    main

    The GoogleSheets trait provides a sheets() method. If your model or an imported namespace already uses the name sheets, you may encounter conflicts. You can use the use ... { ... } syntax to alias the trait's method if necessary.

    use GoogleSheets { 
        GoogleSheets::sheets as googlesheets;
    }
  4. Compare Google Sheets authentication methods

    main

    Choose an authentication method based on your application's needs:

    MethodUse CaseUser InteractionAccess ScopeComplexity
    Service AccountServer-to-server, automated systemsNone requiredSpecific spreadsheets you own/shareMedium
    OAuth 2.0User-facing applicationsUser consent requiredUser's own spreadsheetsHigh
    API KeyPublic data onlyNone requiredPublic spreadsheets onlyLow

    Note: API Key authentication is read-only and only works for publicly shared spreadsheets.

  5. Automatically refresh OAuth tokens

    main

    The package automatically handles token refreshing when using setAccessToken() if a valid refresh_token is provided in the array. To persist the newly refreshed access token, you should retrieve the updated token from the package after the call.

    $token = [
        'access_token' => $user->google_access_token,
        'refresh_token' => $user->google_refresh_token,
        'expires_in' => $user->google_expires_in,
        'created' => $user->google_token_created,
    ];
    
    // This will automatically refresh the token if expired
    Sheets::setAccessToken($token)->spreadsheet('id')->sheet('Sheet1')->all();
    
    // Get the updated token after refresh
    $updatedToken = Sheets::getAccessToken();
    if ($updatedToken) {
        $user->update([
            'google_access_token' => $updatedToken['access_token'],
            'google_token_created' => time(),
        ]);
    }
  6. Configure Google Cloud Console for OAuth 2.0

    main

    To use OAuth 2.0, you must first set up your project in the Google Cloud Console:

    1. Enable APIs: Navigate to APIs & Services > Library and enable both the Google Sheets API and the Google Drive API.
    2. Create Credentials: Go to APIs & Services > Credentials and select Create Credentials > OAuth client ID.
    3. Configure Consent Screen: If prompted, choose External, provide an app name and support email, and add these scopes:
      • https://www.googleapis.com/auth/spreadsheets
      • https://www.googleapis.com/auth/drive
    4. Set Application Type: Choose Web application.
    5. Authorized Redirect URIs: Add your callback URL (e.g., http://localhost:8000/auth/google/callback for local dev or https://yourdomain.com/auth/google/callback for production).
    6. Save Credentials: Copy the generated Client ID and Client Secret.
  7. Install the Laravel Google Sheets package

    main

    Install the package via Composer. Ensure your environment meets the requirements: PHP >= 8.3 and Laravel >= 12.0.

    After installation, publish the configuration file and enable the Google Sheets API and Google Drive API in your Google Cloud Console.

    composer require revolution/laravel-google-sheets
    php artisan vendor:publish --tag="google-config"
  8. Use the GoogleSheets trait for user-specific access

    main

    To allow a User model to interact with Google Sheets using their own credentials, add the Revolution\Google\Sheets\Traits\GoogleSheets trait to your model.

    You must implement the abstract method sheetsAccessToken() which returns an array containing the user's OAuth 2.0 credentials. This allows the trait to automatically handle authentication when calling the sheets() method on the model instance.

    <?php
    
    namespace App;
    
    use Illuminateoundationoundation\Auth\User as Authenticatable;
    use Revolution\Google\Sheets\Traits\GoogleSheets;
    
    class User extends Authenticatable
    {
        use GoogleSheets;
    
        /**
         * Implement the required abstract method to provide OAuth credentials.
         *
         * @return array
         */
        protected function sheetsAccessToken()
        {
            return [
                'access_token'  => $this->access_token,
                'refresh_token' => $this->refresh_token,
                'expires_in'    => $this->expires_in,
                'created'       => $this->created->timestamp,
            ];
        }
    }
  9. Configure Service Account using a JSON string in .env

    main

    For environments like GitHub Actions or containerized deployments where managing separate files is difficult, you can store the entire JSON credential content as a string in your .env file.

    1. Set GOOGLE_SERVICE_ACCOUNT_JSON_LOCATION to the raw JSON string in your .env.
    2. Update config/google.php to decode the string:
    // config/google.php
    'service' => [
        'enable' => env('GOOGLE_SERVICE_ENABLED', false),
        'file' => json_decode(env('GOOGLE_SERVICE_ACCOUNT_JSON_LOCATION', ''), true),
    ],
  10. Convert sheet rows to associative arrays using headers

    main

    The recommended way to process data is to retrieve rows as a Laravel Collection and then use Sheets::collection() to map the first row (headers) as keys for the subsequent rows.

    use Revolution\Google\Sheets\Facades\Sheets;
    
    // get() returns Laravel Collection
    $rows = Sheets::sheet('Sheet 1')->get();
    
    $header = $rows->pull(0);
    $values = Sheets::collection(header: $header, rows: $rows);
    
    // $values is now a collection of associative arrays:
    // [['id' => '1', 'name' => 'name1', ...], ...]