How to use another field for authentication in Laravel?

Viewed 971

In the manual I can read:

By default, Laravel uses the email field for authentication. If you would like to customize this, you may define a username method on your LoginController

However in my case I would like to use the unique_id field which is provided by my company to authenticate my user. This field is not a username so I feel bad about using the username() method to get this. Is there another way to tell Laravel Authentication to use something else than email to authentify my users?

3 Answers

You can override validateLogin and credentials methods in your Auth/LoginController

protected function validateLogin(Request $request)
{
    $request->validate([
        'unique_id' => 'required',
        'password' => 'required|string',
    ]);
}

protected function credentials(Request $request)
{
    return array_merge($request->only('unique_id', 'password'));
}

Ignore the fact that the method is called username() and go for it.

You can overwrite username() method in App\Http\Controllers\Auth\LoginController::class like this:

/**
* Get the login username to be used by the controller
* You Username will be User $unique_id
*/
public function username()
{
    return 'unique_id'
}
Related