Skip to content

Instantly share code, notes, and snippets.

@tillkruss
Last active November 8, 2021 12:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tillkruss/e531b00a3a03ad1b99565f96cbd34fa7 to your computer and use it in GitHub Desktop.
Save tillkruss/e531b00a3a03ad1b99565f96cbd34fa7 to your computer and use it in GitHub Desktop.
Case-insensitive PostgreSQL eloquent user provider for Laravel 5.
<?php
namespace App\Providers;
use Auth;
use App\Support\EloquentUserProvider;
class AuthServiceProvider extends ServiceProvider
{
public function boot(GateContract $gate)
{
Auth::provider('eloquent', function ($app, $config) {
return new EloquentUserProvider($app['hash'], $config['model']);
});
}
}
<?php
namespace App\Support\Auth;
use Illuminate\Support\Str;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Query\Grammars\PostgresGrammar;
use Illuminate\Auth\EloquentUserProvider as UserProvider;
class EloquentUserProvider extends UserProvider
{
/**
* Retrieve a user by the given credentials.
*
* @param array $credentials
* @return \Illuminate\Contracts\Auth\Authenticatable|null
*/
public function retrieveByCredentials(array $credentials)
{
if (empty($credentials)) {
return;
}
return $this->createModel()
->newQuery()
->where(function ($query) use ($credentials) {
foreach ($credentials as $key => $value) {
if ($this->isPostgresGrammar($query) && in_array($key, ['email', 'username'])) {
$query->whereRaw("LOWER({$key}) = LOWER(:value)", ['value' => $value]);
} elseif (! Str::contains($key, 'password')) {
$query->where($key, $value);
}
}
})
->first();
}
protected function isPostgresGrammar(Builder $query)
{
return $query->getQuery()->getGrammar() instanceof PostgresGrammar;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment