October 15, 2015 15:26

By default, Laravel logs users in with their email and password. In some cases you might want them to use a username instead. This is pretty simple, just set the $username property on the AuthController class:

class AuthController extends Controller
{
    ...
    protected $username = 'username';
}

The AuthController uses the AuthenticatesUsers trait, which checks if the $username property is set, and if not, defaults to 'email'

If you want users to have the choice of logging in with email or username, it's a little more complex. You'll have to override the postLogin method in your controller.

class AuthController extends Controller
{
    use AuthenticatesAndRegistersUsers {
        AuthenticatesAndRegistersUsers::postLogin as laravelPostLogin;
    }

    /**
     * Login with email or username
     *
     * @param  Request  $request
     */
    public function postLogin(Request $request)
    {
        $field = filter_var($request->input('email'), FILTER_VALIDATE_EMAIL) ? 'email' : 'username';
        $request->merge([$field => $request->input('email')]);
        $this->username = $field;

        return self::laravelPostLogin($request);
    }
}

To break that code down, first we use the trait, but we want to rename the original postLogin method so that we can use it later.

Then inside our postLogin method, we check if the email field that we're receiving is an email address or not. This assumes that you have some restrictions on usernames, e.g. that they're alphanumeric, or at the very least, don't allow the @ character.

Then it sets the $username attribute as either 'email' or 'username'.

Finally, it calls the laravelPostLogin method, which we had reassigned earlier, so that Laravel continues the login as before. That way we don't have to rewrite any of the logic in that original method.

Laravel, PHP