Google Custom Search Engine in Your Laravel Application

In today’s digital age, providing efficient search functionality on your website is crucial for enhancing user experience. Google Custom Search Engine (CSE) offers a powerful and flexible solution for integrating robust search capabilities into your site. In this blog, we’ll walk you through the process of integrating Google CSE into a Laravel application, ensuring you deliver the best search experience to your users.

Table of Contents

Introduction to Google Custom Search Engine
Prerequisites
Setting Up Google Custom Search Engine
Integrating Google CSE into Laravel
Displaying Search Results

1. Introduction to Google Custom Search Engine

Google Custom Search Engine (CSE) allows you to harness the power of Google’s search technology and tailor it to your specific needs. Whether you’re running a blog, an e-commerce site, or a content-heavy portal, Google CSE can significantly improve the efficiency and relevance of search results on your site.

2. Prerequisites

Before we begin, ensure you have the following:

  • A Laravel application set up
  • Basic knowledge of Laravel and PHP
  • A Google account to create and manage your custom search engine

3. Setting Up Google Custom Search Engine

Step 1: Create a Custom Search Engine

  1. Go to the Google Custom Search Engine page.
  2. Click on “Add” to create a new search engine.
  3. Enter the sites you want to include in your search engine.
  4. Click “Create” and take note of your search engine ID (cx).

Step 2: Obtain an API Key

  1. Go to the Google Cloud Console.
  2. Create a new project or select an existing one.
  3. Navigate to “APIs & Services” > “Credentials”.
  4. Click on “Create Credentials” and select “API Key”.
  5. Enable the “Custom Search API” for your project.

4. Integrating Google CSE into Laravel

Step 1: Setting Up the Environment

Add your Google API key and search engine ID to your .env file:

GOOGLE_API_KEY=your_api_key
GOOGLE_SEARCH_ENGINE_ID=your_search_engine_id

Step 2: Create a Search Controller

Generate a controller to handle search requests:

php artisan make:controller SearchController
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;

class SearchController extends Controller
{
     $apiKey = env('GOOGLE_API_KEY');
     $cx = env('GOOGLE_SEARCH_ENGINE_ID');

    public function index(Request $request)
    {
        $query = $request->input('query');
        $results = null;

        if ($query) {
            $results = $this->fetchGoogleResults($query);
        }

        return view('search.index', compact('results', 'query'));
    }

    private function fetchGoogleResults($query, $startIndex = 1)
    {
        $resultsPerPage = 10;
        $start = ($startIndex - 1) * $resultsPerPage + 1;

        $url = "https://www.googleapis.com/customsearch/v1?key=$apiKey&cx=$cx&q=" . urlencode($query);

        $response = file_get_contents($url);

        return json_decode($response, true);
    }
}

Step 3: Define Routes

Add a route to handle search requests in routes/web.php:

use App\Http\Controllers\SearchController;

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

Step 4: Create a Search Form


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Google Custom Search</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body>
    <div class="container mt-5">
        <h1 class="mb-4">Google Custom Search</h1>
        <form method="GET" action="{{ route('search.index') }}" class="form-inline mb-4">
            <input type="text" name="query" class="form-control mr-sm-2" placeholder="Search" value="{{ request('query') }}">
            <button type="submit" class="btn btn-primary">Search</button>
        </form>

        @if($results)
            <h2>Search Results for "{{ $query }}"</h2>
            <ul class="list-group">
                @foreach($results['items'] as $item)
                    <li class="list-group-item">
                        <h4><a href="{{ $item['link'] }}" target="_blank">{{ $item['title'] }}</a></h4>
                        <p>{{ $item['snippet'] }}</p>
                    </li>
                @endforeach
            </ul>

            <!-- Pagination (Previous and Next buttons) -->
            <nav aria-label="Search results pages" class="mt-4">
                <ul class="pagination">
                    @if(isset($results['queries']['previousPage']))
                        <li class="page-item">
                            <a class="page-link" href="{{ route('search.index', ['query' => $query, 'start' => $results['queries']['previousPage'][0]['startIndex']]) }}" aria-label="Previous">
                                <span aria-hidden="true">&laquo; Previous</span>
                            </a>
                        </li>
                    @endif

                    @if(isset($results['queries']['nextPage']))
                        <li class="page-item">
                            <a class="page-link" href="{{ route('search.index', ['query' => $query, 'start' => $results['queries']['nextPage'][0]['startIndex']]) }}" aria-label="Next">
                                <span aria-hidden="true">Next &raquo;</span>
                            </a>
                        </li>
                    @endif
                </ul>
            </nav>
        @endif
    </div>
</body>
</html>

Output:-

5. Conclusion

Integrating Google Custom Search Engine into your Laravel application is a straightforward process that can greatly enhance the search capabilities of your site. By following this guide, you can provide your users with powerful, accurate, and efficient search functionality, leveraging Google’s unparalleled search technology.

Related Posts

Inside Mumbai’s Live Entertainment Scene: A Local’s Guide to Shows, Venues, and Smart Booking

Ask ten Mumbai residents how they spend a Friday night, and you will hear ten completely different answers. One friend might be queuing outside a sunlit theatre…

Read More

Step-by-Step Mumbai Transit and City Guide for Visitors and New Residents

Most people meet Mumbai through two extremes: either a breathless movie montage of Marine Drive at sunset, or a horror story about squeezing onto a crowded commuter…

Read More

Essential NoOps Automation Tools for Declarative Cloud Infrastructure

Spend a week inside a busy engineering organization and you will spot a familiar bottleneck. Talented developers write new features in hours, yet getting a test environment…

Read More

Engineering Operations Readiness: Evaluating Services Before and After Launch

Introduction Most engineering organizations do not lack tools. They lack an honest map — a clear understanding of where they stand, which capabilities are genuinely missing, and…

Read More

From Unboxing to Daily Mastery: A Simple iPhone and Mac Checklist

Introduction If you own an Apple device, you have probably asked at least one of these questions: Is my iPhone getting the new update? How do I…

Read More

NoOpsSchool Explained: Learning, Certification, and Automation Help in One Place

It is 9 p.m., and a system admin is fixing the same fault she fixed last week. A disk filled up. A service stopped. She runs the…

Read More
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
0
Would love your thoughts, please comment.x
()
x