Last Updated: July 17, 2021
·
296
· emjayess

Laravel Eloquent: mysql-or-pgsql case-insensitive string matching 'search' for models

<?php

namespace App;

use Illuminate\Database\Eloquent\{Model, Builder};

class Widget extends Model
{

    public function scopeSearch(Builder $queryBuilder, $pattern)
    {
        $pattern = '%'.$pattern.'%';

        $like = ( env('DB_CONNECTION') == 'pgsql' )
            // postgresql case-insensitive match with ILIKE
            ? 'ilike'
            // mysql (or compatible) match with LIKE
            : 'like'
        ;

        return $queryBuilder
            ->where('name', $like, $pattern)
            ->orWhere('description', $like, $pattern)
        ;
    }
}

1 Response
Add your response