Laravel supports multi-field logon. many websites now provide this function. Users can log on to the website by email, mobile phone number, or nickname. The following is an example in Laravel (5.1).
The basic principles of the three methods are the same.
1. Method 1
Use Laravel's built-in authentication system to modify/app/Http/Controllers/Auth/AuthController. php file, rewrite method (file where the original method is located/vendor/laravel/framework/src/Illuminate/Foundation/Auth/AuthenticatesUsers. php ):
Namespace App \ Http \ Controllers \ Auth ;...... use Illuminate \ Http \ Request; // add the class AuthController extends Controller {protected $ username = 'login ';.... protected function getCredentials (Request $ request) {$ login = $ request-> get ('login'); $ field = filter_var ($ login, FILTER_VALIDATE_EMAIL )? 'Email ': 'name'; return [$ field => $ login, 'password' => $ request-> get ('password'),] ;}}
2. Method 2
Modify the/app/Http/Controllers/Auth/AuthController. php file. this is also a method to use Laravel's built-in authentication system.
Namespace App \ Http \ Controllers \ Auth ;...... use Illuminate \ Http \ Request; // add the class AuthController extends Controller {// modify the use cases here, ThrottlesLogins {AuthenticatesAndRegistersUsers: postLogin as laravelPostLogin ;}...... // add the public function postLogin (Request $ request) {$ field = filter_var ($ request-> input ('login'), FILTER_VALIDATE_EMAIL )? 'Email ': 'name'; $ request-> merge ([$ field => $ request-> input ('login')]); $ this-> username = $ field; return self: laravelPostLogin ($ request );}}
3. Method 3
Rewrite login function
LoginRequest. php:
public function rules(){ return [ 'login' => 'required', 'password' => 'required' ];}
AuthController. php:
public function login(LoginRequest $request){ $field = filter_var($request->input('login'), FILTER_VALIDATE_EMAIL) ? 'email' : 'username'; $request->merge([$field => $request->input('login')]); if ($this->auth->attempt($request->only($field, 'password'))) { return redirect('/'); } return redirect('/login')->withErrors([ 'error' => 'These credentials do not match our records.', ]);}
This article is a special topic: Laravel tips
- Previous article: Laravel changed the default field name for logon email