简体   繁体   中英

Login with either email or phone in Laravel 5.2

I'm new in Laravel and I'm developing an application that will require users to log in with either email (minority) or their phone number (majority). Currently I'm using the default Laravel auth with modified registration to allow users to provide their phone number. The solutions I have found are showing how to log in with a username instead of an email. How can I achieve this?. I'm running Laravel 5.2 with PHP 7.0

Here is my User model:

protected $fillable = ['firstname', 'lastname', 'email','phone','account_type','county','sub_county', 'password',];

protected $hidden = ['password', 'remember_token',];

Here is my AuthenticateUsers.php:

 /**
 * Get the needed authorization credentials from the request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return array
 */
protected function getCredentials(Request $request)
{
    return $request->only($this->loginUsername(), 'password');
}

/**
 * Validate the user login request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return void
 */
protected function validateLogin(Request $request)
{
    $this->validate($request, [
        $this->loginUsername() => 'required', 'password' => 'required',
    ]);
}

/**
 * Get the login username to be used by the controller.
 *
 * @return string
 */
public function loginUsername()
{
    return property_exists($this, 'username') ? $this->username : 'email';
}

Email input field in my login form:

<div class="form-group{{ $errors->has('email') ? ' has-error' : '' }}">
<label class="col-md-4 control-label">E-Mail Address</label>
<div class="col-md-6">
<input type="text" class="form-control" name="email" value="{{ old('email')    }}">

@if ($errors->has('email'))
<span class="help-block">
<strong>{{ $errors->first('email') }}</strong>
</span>
@endif
</div>
</div>

@if ($errors->has('email'))
<span class="help-block">
<strong>{{ $errors->first('email') }}</strong>
</span>
@endif
</div>
</div>

在您的loginUsername函数中,进行以下更改以在使用电子邮件默认值之前检查请求是否具有电话属性。

public function loginUsername($request) { return $request->has('phone') ? 'phone' : 'email'; }

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