PHP code example of revolution / laravel-google-searchconsole

1. Go to this page and download the library: Download revolution/laravel-google-searchconsole library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

revolution / laravel-google-searchconsole example snippets


'google' => [
    'client_id'     => env('GOOGLE_CLIENT_ID'),
    'client_secret' => env('GOOGLE_CLIENT_SECRET'),
    'redirect'      => env('GOOGLE_REDIRECT_URI'),
],

'client_id'        => env('GOOGLE_CLIENT_ID'),
'client_secret'    => env('GOOGLE_CLIENT_SECRET'),
'redirect_uri'     => env('GOOGLE_REDIRECT_URI'),
'scopes'           => [\Google\Service\Webmasters::WEBMASTERS],
'access_type'      => 'offline',
'prompt'           => 'consent select_account',

'scopes' => [\Google\Service\Webmasters::WEBMASTERS],

// config/google.php
'service' => [
    'file' => json_decode(env('GOOGLE_SERVICE_ACCOUNT_JSON_LOCATION', ''), true),
],



namespace App\Search;

use Revolution\Google\SearchConsole\Query\AbstractQuery;

class YourQueryName extends AbstractQuery
{
    public function init(): void
    {
        // Define your query parameters here
    }
}

$this->setStartDate('2024-01-01');                    // Start date (YYYY-MM-DD)
$this->setEndDate('2024-01-31');                      // End date (YYYY-MM-DD)
$this->setStartDate(now()->subDays(30)->toDateString()); // Dynamic dates

$this->setDimensions(['query']);           // Group by search queries
$this->setDimensions(['page']);            // Group by pages
$this->setDimensions(['country']);         // Group by countries
$this->setDimensions(['device']);          // Group by device types
$this->setDimensions(['searchAppearance']); // Group by search appearance
$this->setDimensions(['query', 'page']);   // Multiple dimensions

// Filter by specific queries
$this->setDimensionFilterGroups([
    [
        'filters' => [
            [
                'dimension' => 'query',
                'operator' => 'contains',
                'expression' => 'laravel'
            ]
        ]
    ]
]);

// Filter by specific pages
$this->setDimensionFilterGroups([
    [
        'filters' => [
            [
                'dimension' => 'page',
                'operator' => 'equals',
                'expression' => 'https://example.com/page'
            ]
        ]
    ]
]);

$this->setRowLimit(100);                   // Limit results (max 25,000)
$this->setStartRow(0);                     // Pagination offset
$this->setAggregationType(['auto']);       // Aggregation type
$this->setDataState('final');              // 'final' or 'fresh' data



namespace App\Search;

use Revolution\Google\SearchConsole\Query\AbstractQuery;

class TopPagesQuery extends AbstractQuery
{
    public function init(): void
    {
        $this->setStartDate(now()->subDays(30)->toDateString());
        $this->setEndDate(now()->toDateString());
        $this->setDimensions(['page']);
        $this->setRowLimit(50);
        $this->setDataState('final');
    }
}



namespace App\Search;

use Revolution\Google\SearchConsole\Query\AbstractQuery;

class MobileQueriesQuery extends AbstractQuery
{
    public function init(): void
    {
        $this->setStartDate(now()->subDays(7)->toDateString());
        $this->setEndDate(now()->toDateString());
        $this->setDimensions(['query']);
        
        // Filter for mobile devices only
        $this->setDimensionFilterGroups([
            [
                'filters' => [
                    [
                        'dimension' => 'device',
                        'operator' => 'equals',
                        'expression' => 'mobile'
                    ]
                ]
            ]
        ]);
        
        $this->setRowLimit(100);
    }
}



namespace App\Search;

use Revolution\Google\SearchConsole\Query\AbstractQuery;

class CountryPerformanceQuery extends AbstractQuery
{
    public function init(): void
    {
        $this->setStartDate(now()->subMonths(3)->toDateString());
        $this->setEndDate(now()->toDateString());
        $this->setDimensions(['country', 'query']);
        $this->setRowLimit(200);
        $this->setAggregationType(['auto']);
    }
}



namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Laravel\Socialite\Facades\Socialite;
use Revolution\Google\SearchConsole\Facades\SearchConsole;
use App\Search\TopPagesQuery;

class GoogleSearchConsoleController extends Controller
{
    public function redirectToGoogle()
    {
        return Socialite::driver('google')
            ->scopes(config('google.scopes'))
            ->with([
                'access_type'     => config('google.access_type'),
                'prompt' => config('google.prompt'),
            ])
            ->redirect();
    }
    
    public function handleGoogleCallback()
    {
        $user = Socialite::driver('google')->user();
        
        // Store tokens in your database
        auth()->user()->update([
            'google_access_token' => $user->token,
            'google_refresh_token' => $user->refreshToken,
        ]);
        
        return redirect()->route('dashboard');
    }
    
    public function getSearchConsoleData(Request $request)
    {
        $token = [
            'access_token' => auth()->user()->google_access_token,
            'refresh_token' => auth()->user()->google_refresh_token,
        ];
        
        // Create and execute query
        $query = new TopPagesQuery();
        $result = SearchConsole::setAccessToken($token)
                              ->query('https://example.com/', $query);
        
        return response()->json($result);
    }
}



namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Revolution\Google\SearchConsole\Traits\WithSearchConsole;

class User extends Authenticatable
{
    use WithSearchConsole;
    
    protected $fillable = [
        'name', 'email', 'google_access_token', 'google_refresh_token'
    ];
    
    protected function tokenForSearchConsole(): array
    {
        return [
            'access_token' => $this->google_access_token,
            'refresh_token' => $this->google_refresh_token,
        ];
    }
}

use App\Search\TopPagesQuery;

$user = User::find(1);
$query = new TopPagesQuery();

// The searchconsole() method automatically handles authentication
$result = $user->searchconsole()->query('https://example.com/', $query);
$sites = $user->searchconsole()->listSites();



namespace App\Services;

use Revolution\Google\SearchConsole\Facades\SearchConsole;
use App\Search\TopPagesQuery;
use App\Search\MobileQueriesQuery;
use App\Search\CountryPerformanceQuery;

class SearchConsoleService
{
    public function getTopPages(string $siteUrl): object
    {
        $query = new TopPagesQuery();
        
        // Service Account authentication is automatic
        return SearchConsole::query($siteUrl, $query);
    }
    
    public function getMobileQueries(string $siteUrl): object
    {
        $query = new MobileQueriesQuery();
        return SearchConsole::query($siteUrl, $query);
    }
    
    public function getCountryPerformance(string $siteUrl): object
    {
        $query = new CountryPerformanceQuery();
        return SearchConsole::query($siteUrl, $query);
    }
    
    public function getAllSites(): object
    {
        return SearchConsole::listSites();
    }
    
    public function getSiteInfo(string $siteUrl): object
    {
        return SearchConsole::listSites(['siteUrl' => $siteUrl]);
    }
}



namespace App\Console\Commands;

use Illuminate\Console\Command;
use Revolution\Google\SearchConsole\Facades\SearchConsole;
use App\Search\TopPagesQuery;

class FetchSearchConsoleData extends Command
{
    protected $signature = 'searchconsole:fetch {site_url}';
    protected $description = 'Fetch Search Console data for a site';
    
    public function handle()
    {
        $siteUrl = $this->argument('site_url');
        $query = new TopPagesQuery();
        
        try {
            $result = SearchConsole::query($siteUrl, $query);
            
            $this->info("Found {$result->rowCount} results:");
            
            foreach ($result->rows as $row) {
                $this->line("Page: {$row->keys[0]}");
                $this->line("  Clicks: {$row->clicks}");
                $this->line("  Impressions: {$row->impressions}");
                $this->line("  CTR: " . round($row->ctr * 100, 2) . "%");
                $this->line("  Position: " . round($row->position, 1));
                $this->line("");
            }
        } catch (\Exception $e) {
            $this->error("Error fetching data: " . $e->getMessage());
        }
    }
}

use Revolution\Google\SearchConsole\Facades\SearchConsole;

// Set access token (OAuth only)
SearchConsole::setAccessToken($token);

// Execute a query
SearchConsole::query($siteUrl, $queryObject);

// List all sites
SearchConsole::listSites();

// List sites with parameters
SearchConsole::listSites(['siteUrl' => 'https://example.com/']);

$result = SearchConsole::query($siteUrl, $query);

// Access the data
echo $result->rowCount;           // Number of results
echo $result->responseAggregationType; // Aggregation type used

foreach ($result->rows as $row) {
    print_r($row->keys);          // Array of dimension values
    echo $row->clicks;            // Number of clicks
    echo $row->impressions;       // Number of impressions
    echo $row->ctr;              // Click-through rate (0-1)
    echo $row->position;         // Average position (1+)
}

$result = SearchConsole::query($siteUrl, $query);

// Safely access properties with default values
$rowCount = data_get($result, 'rowCount', 0);
$aggregationType = data_get($result, 'responseAggregationType', 'unknown');

// Access nested properties safely
foreach ($result->rows as $row) {
    $clicks = data_get($row, 'clicks', 0);
    $impressions = data_get($row, 'impressions', 0);
    $ctr = data_get($row, 'ctr', 0.0);
    $position = data_get($row, 'position', 0.0);
    
    // Handle optional or nested properties
    $firstKey = data_get($row, 'keys.0', 'N/A');
}

$result = SearchConsole::query($siteUrl, $query);

// Convert rows to a Laravel Collection for powerful data manipulation
$rows = collect($result->rows);

// Filter rows with high CTR
$highCtrRows = $rows->filter(fn($row) => $row->ctr > 0.05);

// Sort by impressions (descending)
$sortedRows = $rows->sortByDesc('impressions');

// Get top 10 pages by clicks
$topPages = $rows->sortByDesc('clicks')->take(10);

// Transform data structure
$pageData = $rows->map(function ($row) {
    return [
        'page' => data_get($row, 'keys.0', 'Unknown'),
        'metrics' => [
            'clicks' => $row->clicks,
            'impressions' => $row->impressions,
            'ctr' => round($row->ctr * 100, 2) . '%',
            'position' => round($row->position, 1),
        ]
    ];
});

// Group by device type (if querying by device dimension)
$deviceGroups = $rows->groupBy(fn($row) => data_get($row, 'keys.0', 'unknown'));

// Calculate totals
$totalClicks = $rows->sum('clicks');
$totalImpressions = $rows->sum('impressions');
$averagePosition = $rows->average('position');