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)
;
}
}
Written by matt j. sorenson
Related protips
1 Response
over 1 year ago
·
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Laravel
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#