Skip to content

Instantly share code, notes, and snippets.

@eliurkis
Created April 26, 2019 13:36
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 eliurkis/73647cdf6d69b23022dfcf054aed12ac to your computer and use it in GitHub Desktop.
Save eliurkis/73647cdf6d69b23022dfcf054aed12ac to your computer and use it in GitHub Desktop.
Make login case insensitive for PostgreSQL in Laravel Framework
<?php
namespace App\Providers;
use App\Policies\UserPolicy;
use App\Support\Auth\EloquentUserProvider;
use App\User;
use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Auth;
class AuthServiceProvider extends ServiceProvider
{
/**
* The policy mappings for the application.
*
* @var array
*/
protected $policies = [
User::class => UserPolicy::class,
];
/**
* Register any authentication / authorization services.
*
* @return void
*/
public function boot()
{
$this->registerPolicies();
Auth::provider('eloquent', function ($app, $config) {
return new EloquentUserProvider($app['hash'], $config['model']);
});
}
}
<?php
namespace App\Support\Auth;
use Illuminate\Auth\EloquentUserProvider as UserProvider;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Query\Grammars\PostgresGrammar;
use Illuminate\Support\Str;
class EloquentUserProvider extends UserProvider
{
/**
* Retrieve a user by the given credentials.
*
* @param array $credentials
*
* @return Builder|\Illuminate\Database\Eloquent\Model|object|void
*/
public function retrieveByCredentials(array $credentials)
{
if (empty($credentials) ||
(count($credentials) === 1 &&
array_key_exists('password', $credentials))) {
return;
}
// First we will add each credential element to the query as a where clause.
// Then we can execute the query and, if we found a user, return it in a
// Eloquent User "model" that will be utilized by the Guard instances.
$query = $this->newModelQuery();
foreach ($credentials as $key => $value) {
if (Str::contains($key, 'password')) {
continue;
}
if ($this->isPostgresGrammar($query) && in_array($key, ['email', 'username'])) {
$query->whereRaw("LOWER({$key}) = LOWER(:value)", ['value' => $value]);
} elseif (is_array($value) || $value instanceof Arrayable) {
$query->whereIn($key, $value);
} else {
$query->where($key, $value);
}
}
return $query->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