personal-logo
Freelancer Web Developer in Nepal with 15+ Years of Experience

Kokil Thapa is an experienced full-stack web developer focused on building fast, secure, and scalable web applications. He helps businesses and individuals create SEO-friendly, user-focused digital platforms designed for long-term growth.

Implementing Google Custom Search in Laravel

Search functionality is one of the most important features of modern websites. Whether you're building a documentation portal, e-commerce platform, blog, or enterprise-level system, users expect fast and relevant search results. Instead of building a search engine from scratch, many developers prefer leveraging Google Custom Search Engine (CSE)—a powerful tool that brings the accuracy and performance of Google's search into your Laravel application.

Google Custom Search allows you to index your entire website (or multiple domains) and perform lightning-fast searches with Google’s infrastructure. Integrating this into Laravel becomes effortless with the jan-drda/laravel-google-custom-search-engine package.

In this comprehensive guide, we’ll walk through installation, configuration, real-world usage, advanced tips, and best practices for implementing Google Custom Search within any Laravel project.


1. Understanding Google Custom Search Engine (CSE)

Before diving into the Laravel implementation, let’s quickly revisit what CSE offers:

Search capabilities for:

  • A single website

  • Multiple websites

  • Entire web

Highly relevant results (Google-powered)

Customizable:

  • Result formatting

  • Languages

  • Layouts

  • Ranking adjustments

Flexible output

You can fetch structured search results in JSON format and format them however you want inside Laravel.

This makes Google CSE a perfect solution for websites that need search functionality without building full indexing logic manually.


2. Installing the Laravel Google Custom Search Package

The recommended package for integration is:

jan-drda/laravel-google-custom-search-engine

Install it via Composer:

composer require jan-drda/laravel-google-custom-search-engine

This will install the package and make it available in your Laravel project.


3. Registering the Provider and Facade

If you’re using Laravel 8 or newer with auto-discovery, you may not need to add the provider manually.
However, if auto-discovery is disabled, add this manually inside config/app.php.

Add the Service Provider

'providers' => [ ... JanDrda\LaravelGoogleCustomSearchEngine\LaravelGoogleCustomSearchEngineProvider::class, ];

Add the Facade Alias

'aliases' => [ ... 'GoogleCseSearch' => JanDrda\LaravelGoogleCustomSearchEngine\Facades\LaravelGoogleCustomSearchEngineProvider::class, ];

4. Publish the Configuration File

Publishing the config file gives you full control over API credentials and settings:

php artisan vendor:publish --provider="JanDrda\LaravelGoogleCustomSearchEngine\LaravelGoogleCustomSearchEngineProvider"

This creates:

config/google-custom-search-engine.php

Configuration options:

  • search_engine_id → Your Google CSE ID

  • api_key → The API key from Google Cloud

  • language → Default language for search results

Update them using values from your Google Custom Search dashboard.


5. Setting Up Google CSE

Before using the package, you need:

  • A Google Account

  • A Google Custom Search Engine

  • A Google Cloud API Key


Step-by-Step: Create Google CSE

  1. Visit
    https://cse.google.com/cse/all

  2. Click Add

  3. Enter the website you want to index
    Example:

    https://yourwebsite.com
  4. Copy the Search Engine ID (CX)

  5. Enable the Custom Search API in Google Cloud
    https://console.cloud.google.com/apis/library

  6. Generate an API Key


6. Using the Search Engine in Laravel

Once your setup is ready, you can begin using CSE in your Laravel app.

The main method you’ll use is:

LaravelGoogleCustomSearchEngine::search('search term');

Example Usage:

$results = LaravelGoogleCustomSearchEngine::search('Laravel tutorials'); foreach ($results as $result) { echo $result->title; echo $result->url; echo $result->snippet; }

What the result contains:

  • title: The result title

  • url: The destination URL

  • snippet: Short preview text

  • pagemap (optional): Structured metadata

  • displayLink: Website domain


7. Building a Search Controller in Laravel

Create a controller:

php artisan make:controller SearchController

Example Controller:

namespace App\Http\Controllers; use Illuminate\Http\Request; use LaravelGoogleCustomSearchEngine; class SearchController extends Controller { public function index(Request $request) { $query = $request->input('q'); $results = []; if ($query) { $results = LaravelGoogleCustomSearchEngine::search($query); } return view('search.index', compact('results', 'query')); } }

8. Creating the Search Route

Add this to routes/web.php:

Route::get('/search', [SearchController::class, 'index'])->name('search');

9. Creating the Search Blade View

Create resources/views/search/index.blade.php

 

@if(!empty($results))

Search Results

  • @foreach($results as $result)@endif

    This displays real-time Google-powered results directly in your Laravel view.


    10. Adding Pagination (Optional)

    Google CSE supports pagination using the "start" parameter.

    Example:

    LaravelGoogleCustomSearchEngine::search('Laravel', 10, $startIndex);

    11. Error Handling

    Wrap your API calls in try/catch to handle:

    • API quota limits

    • Invalid API keys

    • Network issues

    • Empty queries

    try { $results = LaravelGoogleCustomSearchEngine::search($query); } catch (\Exception $e) { return back()->withErrors('Error fetching results: ' . $e->getMessage()); }

    12. Best Practices When Using Google CSE in Laravel

    Cache Search Results

    Improve performance by caching repeated query results.

    Validate User Input

    Prevent unnecessary API calls using input length validation.

    Monitor API Quotas

    Google charges for API calls beyond a certain limit.

    Consider Rate Limiting

    Avoid abuse by limiting search requests per minute.

    Customize Snippets

    Format snippets with highlighting, trimming, or keywords.


    Conclusion

    Adding search functionality to your Laravel application becomes incredibly easy with Google Custom Search Engine and the jan-drda/laravel-google-custom-search-engine package. With just a few steps—installing the package, configuring API keys, and writing simple controller logic—you can deliver fast, accurate, and user-friendly search results powered by Google.

    Whether you're running a blog, SaaS platform, or large documentation site, this integration ensures your users can instantly find the information they need.

    For more Laravel tutorials, development guides, and backend engineering insights, follow work published by a seasoned web developer in Nepal who regularly shares practical and modern programming content.

Quick Contact Options
Choose how you want to connect me: