One solution could be to use the official Google API client library for PHP and integrate it into your Laravel project. Here are the steps to do so:
- Install the Google API client library for PHP using Composer:
composer require google/apiclient:^2.0
-
Create a new project in the Google Cloud Console and enable the Search Console API for it.
-
Create a service account and download the JSON key file.
-
In your Laravel project, create a new file
config/google.phpwith the following contents:
<?php
return [
'application_name' => env('GOOGLE_APPLICATION_NAME'),
'service_account_credentials_json' => env('GOOGLE_SERVICE_ACCOUNT_CREDENTIALS_JSON'),
'scopes' => [
'https://www.googleapis.com/auth/webmasters.readonly',
],
];
- Add the following environment variables to your
.envfile:
GOOGLE_APPLICATION_NAME=Your Application Name
GOOGLE_SERVICE_ACCOUNT_CREDENTIALS_JSON=/path/to/your/keyfile.json
- Create a new controller method to fetch data from the Search Console API:
use Google\Client;
use Google\Service\Webmasters;
public function searchConsoleData()
{
$client = new Client();
$client->setApplicationName(config('google.application_name'));
$client->setAuthConfig(config('google.service_account_credentials_json'));
$client->setScopes(config('google.scopes'));
$webmastersService = new Webmasters($client);
$siteUrl = 'https://example.com'; // Replace with your site URL
$startDate = '2022-01-01'; // Replace with your desired start date
$endDate = '2022-01-31'; // Replace with your desired end date
$searchAnalyticsQueryRequest = new Webmasters_SearchAnalyticsQueryRequest();
$searchAnalyticsQueryRequest->setStartDate($startDate);
$searchAnalyticsQueryRequest->setEndDate($endDate);
$searchAnalyticsQueryRequest->setDimensions(['query']);
$searchAnalyticsQueryRequest->setRowLimit(10);
$searchAnalyticsQueryResponse = $webmastersService->searchanalytics->query($siteUrl, $searchAnalyticsQueryRequest);
$rows = $searchAnalyticsQueryResponse->getRows();
// Do something with the data
}
This method fetches the top 10 search queries for your site between the specified dates. You can modify the parameters to fetch different data.
- Call the
searchConsoleDatamethod from a route or a command in your Laravel project.
Note: This solution assumes that you are using Laravel 5.5 or higher, which includes automatic package discovery. If you are using an older version of Laravel, you may need to manually register the Google API client library service provider and facade.