47

Now I'm using something like that for authenticating the user on my base site:

if (Auth::attempt($request->only(['id', 'password']))) {
            //
}

How can I modify this code for using custom column as username? https://laravel.com/docs/5.3/passport#password-grant-tokens

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
tehcpu
  • 934
  • 1
  • 11
  • 23

2 Answers2

105

You can use findForPassport method in your user model.

This method take username as argument, and return user model

For example:

class User extends Authenticatable
{
    use HasApiTokens, Notifiable;

    // ... some code

    public function findForPassport($username) {
        return $this->where('id', $username)->first();
    }
}
Alexander
  • 2,257
  • 1
  • 18
  • 19
  • 1
    How about if the password is also stored in a separate database table? Or if the credentials are validated by a third party API (under the hood)? – Yannick Y Dec 20 '16 at 02:34
  • If your custom colum is called `username` you may want to use `return $this->where('username','=', $username)->first();` – Adam Feb 17 '21 at 13:59
  • what if i have to login with email and mobile number both – swatantra Oct 01 '21 at 09:54
  • @swatantra you can use something like `$this->where(fn($q) => $q->where('email', $username)->orWhere('phone', $username));` – Alexander Oct 05 '21 at 12:54
  • Yeah, exactly I have already done that and it helps, Thanks – swatantra Oct 06 '21 at 08:25
10

A bit too late to answer, but I've been having a hard time trying to figure this out, so for the sake of completeness and to maybe help others in the future.

If you take a look to this part of passport's code you'll see that it also looks for a validateForPassportPasswordGrant method, so in addition to Alexander's answer, that's how you can authenticate an user using custom fields.

Hope it helps someone.

freddieRV
  • 101
  • 3
  • 7