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

Renting a Bike, Scooter, or Car in Japan: A Rider’s Honest Guide to Roads, Rules, and Fleet Tools

Introduction Ask any rider about Japan, and their eyes light up. The roads feel almost unfair. Smooth surfaces. Sharp markings. Drivers who actually follow the rules. Add…

Read More

How Long Does Pilot Training Take? Real Timelines for Every License

Introduction Most people who dream of flying never start. Not because they lack talent. Not because they lack passion. They simply never find a clear answer to…

Read More

Free Blogging Platform Guide: Create a Blog for Free, Publish Articles Online, and Join a Writing Community

Introduction You have ideas worth sharing. Maybe you want to write about technology. Maybe you want to document your travels. Or maybe your business needs a place…

Read More

Offer Letter Management Software: How to Speed Up Candidate Acceptance

Hiring a talented person feels great. The interview went well, and the team said yes to you. Everyone smiles and waits for day one. But then the…

Read More

How TheDataOps Explains Predictive Maintenance in Pipelines

Your data pipelines break down at the worst possible time. You wake up to angry texts from your team because morning reports are blank. You spend hours…

Read More

Customer Reviews and Ratings: Why Verified Feedback Matters Most

Introduction Shopping online in India is exciting today. You can find millions of gadgets, appliances, and tools with just one click. Yet, this massive choice creates a…

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