Visit the Google Cloud Console to start setting up your project. Click
!open this
Create a new project in the Google Cloud Console.
!Create New Project
Navigate to the library section of your Google Cloud project.
!Go to Library
Search for the required APIs and enable them for your project.
!Choose this one
!Enable APIs
Go to the 'Credentials' section after enabling the necessary APIs.
!Credentials Section
Ensure your API key is enabled for editing.
Enable the WebClient and download the JSON file.
Go to your Google Sheet and ensure it is set to 'Share and Edit'.
!Google Sheets Share and Edit
Note that the name you see is the name of the paper, not the sheet.
!Paper Name
Place the downloaded JSON file into the storage directory of your Laravel project.
!JSON File in Storage
Set the following environment variables in your .env
file:
GOOGLE_API_KEY=your-google-api-key
GOOGLE_CLIENT_ID=your-google-client-id
GOOGLE_CLIENT_SECRET=your-google-client-secret
GOOGLE_SERVICE_ACCOUNT_EMAIL=your-service-account-email
GOOGLE_SERVICE_ACCOUNT_JSON=your-json-file-name
GOOGLE_REDIRECT_URL=your-redirect-url
Run the following commands to install the necessary package and publish the configuration:
composer require revolution/laravel-google-sheets
php artisan vendor:publish --provider="PulkitJalan\Google\GoogleServiceProvider" --tag="config"
Create a google.php file in the config folder with the following content:
<?php
return [
'application_name' => env('GOOGLE_APPLICATION_NAME', 'My Laravel Application'),
'client_id' => env('GOOGLE_CLIENT_ID'),
'client_secret' => env('GOOGLE_CLIENT_SECRET'),
'redirect_uri' => env('GOOGLE_REDIRECT_URL'),
'scopes' => [
\Google\Service\Sheets::DRIVE,
\Google\Service\Sheets::SPREADSHEETS,
],
'access_type' => 'offline',
'approval_prompt' => 'force',
'developer_key' => env('GOOGLE_API_KEY'),
'service' => [
'enable' => true,
'file' => env('GOOGLE_SERVICE_ACCOUNT_JSON', storage_path('app/google-service-account.json')),
],
'config' => [],
];
Remember to clear the configuration cache after making changes:
php artisan config:clear
php artisan config:cache
php artisan cache:clear
Get the $spreadsheetId from the URL of the sheet.
!Spread sheet Id
Define the $ordersSheetName
as orders!A2:F6
, which is the name of the sheet paper and its range.
use Revolution\Google\Sheets\Facades\Sheets;
public function index()
{
$spreadsheetId = '1-ftqLjH8-rB2gNRro7uEq8j0j42oGqMvyKOw0v5__bE';
$spreadsheetProductId = '14jNcQTMwAlRcx_JJpNszqovWzuBwrjKWvw4eZeotzJw';
$ordersSheetName = 'orders!A2:f6';
$productsSheetName = 'products!A2:D6';
$orders = Sheets::spreadsheet($spreadsheetId)
->sheet($ordersSheetName)
->get();
$products = Sheets::spreadsheet($spreadsheetProductId)
->sheet($productsSheetName)
->get();
return response()->json(['orders' => $orders, 'products' => $products]);
}