Laravel Eloquent: How to Implement Case-Insensitive Search

Updated: January 17, 2024 By: Guest Contributor Post a comment

Overview

Laravel, the elegant PHP framework, is renowned for the elegance it brings to database manipulation through Eloquent ORM. One crucial feature commonly required in search functionalities is case insensitivity to provide a user-friendly query experience. This article delves into various ways to achieve a case-insensitive search with Laravel Eloquent, progressing from the simplest approaches to more advanced strategies.

Understanding Case Sensitivity in SQL

Before we start, it’s important to note that case sensitivity in search queries depends on the collation set for the database or the specific column you’re querying against. For instance, MySQL’s default collation is ‘utf8mb4_general_ci’, where ‘ci’ stands for case-insensitive, but if your collation is ‘utf8mb4_bin’ for binary, searches would be case-sensitive.

Basic Implementation

The first step in implementing case-insensitive search in Laravel Eloquent is to use the native LIKE operator. When the database collation is case-insensitive, this simple query would suffice:

$users = User::where('name', 'LIKE', "%$searchTerm%")->get();

This approach will work as expected in SQL databases with case-insensitive collation. However, if your database or column specifically has case-sensitive collation, you need to enforce lower or upper casing both on the column values and the search term.

Forcing Case Insensitivity

To manually force a case-insensitive search, you can apply SQL’s LOWER() or UPPER() functions:

$users = User::whereRaw('LOWER(name) LIKE LOWER(?)', ["%$searchTerm%"])
             ->get();

This will convert both the column values and the search term to lower case before performing the comparison, effectively ignoring the case of letters. Ensure you bind the search term as a parameter instead of inserting it directly into the query to prevent SQL injection attacks.

Custom Eloquent Scope

Using LOWER() and UPPER() within your queries can get repetitive. Refactoring this logic into a reusable scope is more efficient:

use Illuminate\Database\Eloquent\Builder;

trait Searchable {
    public function scopeInsensitiveSearch(Builder $query, $column, $value) {
        return $query->whereRaw('LOWER(' . $column . ') LIKE ?', ['%' . strtolower($value) . '%']);
    }
}

After defining the trait, you can use it within your Eloquent models:

class User extends Model {
    use Searchable;

    // Use the scope like so:
    $users = User::insensitiveSearch('name', $searchTerm)->get();
}

This is a tidy and reusable way to perform case-insensitive searches across your application’s Eloquent models.

Advanced: Custom Database Function

If you’re dealing with a lot of text data and case-insensitive searches are a core aspect of your app, it makes sense to implement more advanced solutions. For instance, defining a custom database function or using database extensions such as PostgreSQL’s ILIKE for case-insensitive matching:

$users = User::where('name', 'ILIKE', "%$searchTerm%")->get();

Note that using database-specific functions and features will reduce the portability of your application across different SQL database systems.

Using Search Engines

Finally, if your application has escalated to heavy search operations, consider leveraging a dedicated search engine such as Algolia or Elasticsearch, which naturally support case-insensitive searches and bring additional benefits such as typo tolerance, faceting, and more.

With Laravel Scout, integrating such search engines becomes a breeze. After configuring the search driver in your config/scout.php, you can search with:

$users = User::search($searchTerm)->get();

Under the hood, Laravel Scout will handle the complexity, while you enjoy the powerful features of your chosen search engine.

Conclusion

Implementing case-insensitive search in Laravel Eloquent can range from simple native SQL manipulations to leveraging third-party search engines, depending on your project’s requirements. Using the strategies outlined in this article, you can refine the search functionality of your Laravel applications to enhance user experience and retrieve data without worry about case sensitivity.