Chinmoy Maity Chinmoy Maity - 29 days ago 6
PHP Question

Laravel 4 Auth::attempt using either email or username and password

In laravel for login attempt I generally use something like this:

if (Auth::attempt(array('email' => $usernameinput, 'password' => $password), true))
{
// The user is being remembered...
}


Basically
$usernameinput
will check with
email
from my table.

I was thinking to do it in a different way, like there is
email
,
username
and
password
in my table.
$usernameinput
can be either
email
or
username
field in my table.

How can I
Auth::attempt
with a condition like:

(email==$usernameinput OR username==$usernameinput) AND password == $password

Answer

Well, you could simply check if $usernameinput matches an email pattern and if it does, use the email field, else use the username field. This sounds reasonable because, well, you really shouldn't have any e-mail in your database that doesn't match the pattern. Something like this:

$field = filter_var($usernameinput, FILTER_VALIDATE_EMAIL) ? 'email' : 'username';

if (Auth::attempt(array($field => $usernameinput, 'password' => $password), true)) {
    // ...
}

The other option is to extend Illuminate\Auth\Guard adding the wanted functionality and setting it as the auth component, in a new service provider.