Skip to content

Instantly share code, notes, and snippets.

@EduardoSP6
Last active October 7, 2025 23:35
Show Gist options
  • Select an option

  • Save EduardoSP6/78aeece88d035efb1b71c0fb48521143 to your computer and use it in GitHub Desktop.

Select an option

Save EduardoSP6/78aeece88d035efb1b71c0fb48521143 to your computer and use it in GitHub Desktop.
Authenticate user by other fields through Laravel Passport

How to authenticate user by other fields in Laravel

Authenticate user by other model fields in Laravel 5.x API and Passport.

Model User:

<?php

class User extends Authenticatable implements Transformable
{
    use TransformableTrait;
    use Notifiable;
    use HasApiTokens;
  
    protected $fillable = [
        "registry",
        "cpf",
        "username",
        "password",
    ];
    
    /** 
     * Implement those methods below. This methods can be found at: ../vendor/laravel/passport/src/Bridge/UserRepository.php
     */
    
    public function findForPassport($registry)
    {
        // Find the user by the parameter received, in this case is registry field
        $user = $this->where('registry', '=', $registry)->first();
        if(!$user)
            return null;

        // check if user status is: 1 - enabled
        if($user->status != 1) {
            return null;
        }

        return $user;
    }

    /** Validate password by any field of model user, in this case is cpf field **/
    public function validateForPassportPasswordGrant($password)
    {
        return $this->where('cpf', $password)->first();
    }
 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment