简体   繁体   中英

Laravel - login with phone and username, FILTER_VALIDATE_EMAIL ISSUE

I want my project to have two ways of login, with phone or with username = korisnicko_ime . This is what I did in LoginController :

     /**
     * Login username to be used by the controller.
     *
     * @var string
     */
    protected $username;

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
        $this->username = $this->findUsername();
    }

    /**
     * Get the login username to be used by the controller.
     *
     * @return string
     */
    public function findUsername()
    {
        $login = request()->input('login');
 
        $fieldType = filter_var($login, FILTER_VALIDATE_EMAIL) ? 'email' : 'korisnicko_ime';
 
        request()->merge([$fieldType => $login]);
 
        return $fieldType;
    }
 
    /**
     * Get username property.
     *
     * @return string
     */
    public function username()
    {
        return $this->username;
    }

And I also changed public function username() in AuthenticatesUsers trait like this:

     /**
     * Get the login username to be used by the controller.
     *
     * @return string
     */
    public function username()
    {
        return 'phone';
    }

And my blade looks like this:

<div class="form-group row">
   <label for="login" class="col-sm-4 col-form-label text-md-right">
      {{ __('Username or Phone') }}
   </label>

   <div class="col-md-6">
      <input id="login" type="text" class="form-control{{ $errors->has('korisnicko_ime') || $errors->has('phone') ? ' is-invalid' : '' }}" name="login" value="{{ old('korisnicko_ime') ?: old('phone') }}" required autofocus>

      @if ($errors->has('korisnicko_ime') || $errors->has('phone'))
      <span class="invalid-feedback">
      <strong>{{ $errors->first('korisnicko_ime') ?: $errors->first('phone') }}</strong>
      </span>
      @endif
   </div>
</div>

The problem is in this part of code:

$fieldType = filter_var($login, FILTER_VALIDATE_EMAIL) ? 'email' : 'korisnicko_ime';

if I change email to phone and erase FILTER_VALIDATE_EMAIL then I can only login with my phone and not with korisnicko_ime . What should I do?

How about this:

Basically, you need a way to tell the input whether is a phone number or a username, here is an example to check the input is a phone number, it's very simple you may need to modify for your specific need.

$fieldType = ctype_digit($login) ? 'phone' : 'korisnicko_ime';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM