Append to Google Spreadsheet

Copy & paste this code into a new Livewire component. Make sure you replace the following placeholders:

  • ACCESS_TOKEN: create a new Google Spreadsheet import and copy the access token you get in step 5.
  • SPREADSHEET_ID: enter the Spreadsheet ID of your spreadsheet, which you can find in the URL of the sheet: https://docs.google.com/spreadsheets/d/<this-is-the-spreadsheet-id>.
  • TAB_NAME: the tab name in which the data should be appended. Leave empty to automatically select the first tab.
  • VALUE_1, VALUE_2, ...: the values that should be appended.
<div>
    <button type="button" wire:click="append">
        Append
    </button>
</div>

<?php

use Google_Service_Sheets;
use Google_Service_Sheets_ValueRange;

class AppendToGoogleSheet extends Component
{
    public function append()
    {
        $accessToken = 'ACCESS_TOKEN';
        $spreadsheetId = 'SPREADSHEET_ID';
        $tabName = 'TAB_NAME';
        $values = ['VALUE_1', 'VALUE_2'];

        $client = google($accessToken);
        $service = new Google_Service_Sheets($client);

        if (! $tabName) {
            $spreadsheet = $service->spreadsheets->get($spreadsheetId);
            $sheets = $spreadsheet->getSheets();
            $tabName = $sheets[0]->getProperties()->getTitle();
        }

        $valueRange = new Google_Service_Sheets_ValueRange();
        $valueRange->setValues([
            'values' => $values,
        ]);

        $service->spreadsheets_values->append($spreadsheetId, $tabName, $valueRange, [
            'valueInputOption' => 'USER_ENTERED',
        ]);
    }
}
Previous topic
← Markdown Mail
Next topic
Authentication →