Last Updated: December 21, 2020
·
21
· emjayess

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

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\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