Last active
November 8, 2021 12:38
-
-
Save tillkruss/e531b00a3a03ad1b99565f96cbd34fa7 to your computer and use it in GitHub Desktop.
Case-insensitive PostgreSQL eloquent user provider for Laravel 5.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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']); | |
}); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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