Implementing multi-field login function in Laravel5.4
Recently I encountered a need at work. I need to realize the effect of multi-field login, that is, you can log in using any method of mobile phone or email. Now I will share the solution process, so this article mainly introduces it to you. The relevant information on implementing the multi-field login function based on Laravel5.4 is available. Friends who need it can refer to it. Let’s take a look together.
Preface
Recently, I needed to implement a multi-field login function in a project. To put it simply, you can use username, email or mobile phone Log in any way. So this article will introduce to you the relevant content about Laravel5.4 multi-field login, and share it for your reference and study. Without further ado, let’s take a look at the detailed introduction.
The following content is based on laravel5.4
The method is as follows:
First, use the artisan tool Generate auth module
php artisan make:auth
At this time, an Auth directory will be added to the App\Http\Controllers directory, which is related to registration and login. In the controller, the resources\views directory will also generate some views related to registration and login
Laravel's official documentation says that manual authentication of users requires the attempt method of the Illuminate\Support\Facades\Auth class, as follows:
<?php namespace App\Http\Controllers; use Illuminate\Support\Facades\Auth; class LoginController extends Controller { /** * Handle an authentication attempt. * * @return Response */ public function authenticate() { if (Auth::attempt(['email' => $email, 'password' => $password])) { // Authentication passed... return redirect()->intended('dashboard'); } } }
This method will determine whether there is a matching user in the database based on the parameters you passed in. If it exists and the password is correct, it will return true, otherwise it will return false
Then add the user in LoginController method, but it seemed to have no effect
So we started to observe the implementation mechanism of LoginController and found that it implemented a trait of AuthenticatesUsers. We traced the definition file of this trait and found that this file is what we want
There is a login method in it, which is responsible for processing the logic of login
/** * Handle a login request to the application. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\Response */ public function login(Request $request) { // 表单验证 $this->validateLogin($request); // If the class is using the ThrottlesLogins trait, we can automatically throttle // the login attempts for this application. We'll key this by the username and // the IP address of the client making these requests into this application. // 防止暴力破解,多次登录失败会根据IP锁定 if ($this->hasTooManyLoginAttempts($request)) { $this->fireLockoutEvent($request); return $this->sendLockoutResponse($request); } // 这个就是主要的负责判断数据库中是否存在相应的账号和密码的地方,我们需要重写的就是attemptLogin方法 if ($this->attemptLogin($request)) { return $this->sendLoginResponse($request); } // If the login attempt was unsuccessful we will increment the number of attempts // to login and redirect the user back to the login form. Of course, when this // user surpasses their maximum number of attempts they will get locked out. // 登录失败,失败次数++,防止暴力破解 $this->incrementLoginAttempts($request); // 返回失败响应 return $this->sendFailedLoginResponse($request); }
After analyzing a wave of this file, I found that the main method for determining login is the attemptLogin method. We only need to rewrite this method. Let’s look at it first. See how the original one is written, and rewrite it according to the original one:
/** * Attempt to log the user into the application. * * @param \Illuminate\Http\Request $request * @return bool */ protected function attemptLogin(Request $request) { return $this->guard()->attempt( $this->credentials($request), $request->has('remember') ); }
After the LoginController is rewritten:
public function attemptLogin(Request $request) { $username = $request->input('username'); $password = $request->input('password'); // 验证用户名登录方式 $usernameLogin = $this->guard()->attempt( ['username' => $username, 'password' => $password], $request->has('remember') ); if ($usernameLogin) { return true; } // 验证手机号登录方式 $mobileLogin = $this->guard()->attempt( ['mobile' => $username, 'password' => $password], $request->has('remember') ); if ($mobileLogin) { return true; } // 验证邮箱登录方式 $emailLogin = $this->guard()->attempt( ['email' => $username, 'password' => $password], $request->has('remember') ); if ($emailLogin) { return true; } return false; }
Just use the attempt method to make multiple judgments, as long as it succeeds Return true. If it fails, continue to use other fields to judge. If it is unsuccessful, it will return false
Test, which can achieve multi-field login effect
The above is the detailed content of Implementing multi-field login function in Laravel5.4. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

With the rapid development of social media, Xiaohongshu has become a popular platform for many young people to share their lives and explore new products. During use, sometimes users may encounter difficulties logging into previous accounts. This article will discuss in detail how to solve the problem of logging into the old account on Xiaohongshu, and how to deal with the possibility of losing the original account after changing the binding. 1. How to log in to Xiaohongshu’s previous account? 1. Retrieve password and log in. If you do not log in to Xiaohongshu for a long time, your account may be recycled by the system. In order to restore access rights, you can try to log in to your account again by retrieving your password. The operation steps are as follows: (1) Open the Xiaohongshu App or official website and click the "Login" button. (2) Select "Retrieve Password". (3) Enter the mobile phone number you used when registering your account

When you log in to someone else's steam account on your computer, and that other person's account happens to have wallpaper software, steam will automatically download the wallpapers subscribed to the other person's account after switching back to your own account. Users can solve this problem by turning off steam cloud synchronization. What to do if wallpaperengine downloads other people's wallpapers after logging into another account 1. Log in to your own steam account, find cloud synchronization in settings, and turn off steam cloud synchronization. 2. Log in to someone else's Steam account you logged in before, open the Wallpaper Creative Workshop, find the subscription content, and then cancel all subscriptions. (In case you cannot find the wallpaper in the future, you can collect it first and then cancel the subscription) 3. Switch back to your own steam

Both vivox100s and x100 mobile phones are representative models in vivo's mobile phone product line. They respectively represent vivo's high-end technology level in different time periods. Therefore, the two mobile phones have certain differences in design, performance and functions. This article will conduct a detailed comparison between these two mobile phones in terms of performance comparison and function analysis to help consumers better choose the mobile phone that suits them. First, let’s look at the performance comparison between vivox100s and x100. vivox100s is equipped with the latest

With the rapid development of the Internet, the concept of self-media has become deeply rooted in people's hearts. So, what exactly is self-media? What are its main features and functions? Next, we will explore these issues one by one. 1. What exactly is self-media? We-media, as the name suggests, means you are the media. It refers to an information carrier through which individuals or teams can independently create, edit, publish and disseminate content through the Internet platform. Different from traditional media, such as newspapers, television, radio, etc., self-media is more interactive and personalized, allowing everyone to become a producer and disseminator of information. 2. What are the main features and functions of self-media? 1. Low threshold: The rise of self-media has lowered the threshold for entering the media industry. Cumbersome equipment and professional teams are no longer needed.

Baidu Netdisk can not only store various software resources, but also share them with others. It supports multi-terminal synchronization. If your computer does not have a client downloaded, you can choose to enter the web version. So how to log in to Baidu Netdisk web version? Let’s take a look at the detailed introduction. Baidu Netdisk web version login entrance: https://pan.baidu.com (copy the link to open in the browser) Software introduction 1. Sharing Provides file sharing function, users can organize files and share them with friends in need. 2. Cloud: It does not take up too much memory. Most files are saved in the cloud, effectively saving computer space. 3. Photo album: Supports the cloud photo album function, import photos to the cloud disk, and then organize them for everyone to view.

Xiaohongshu has now been integrated into the daily lives of many people, and its rich content and convenient operation methods make users enjoy it. Sometimes, we may forget the account password. It is really annoying to only remember the account but not be able to log in. 1. How to log in if Xiaohongshu only remembers the account? When we forget our password, we can log in to Xiaohongshu through the verification code on our mobile phone. The specific operations are as follows: 1. Open the Xiaohongshu App or the web version of Xiaohongshu; 2. Click the "Login" button and select "Account and Password Login"; 3. Click the "Forgot your password?" button; 4. Enter your account number. Click "Next"; 5. The system will send a verification code to your mobile phone, enter the verification code and click "OK"; 6. Set a new password and confirm. You can also use a third-party account (such as

As Xiaohongshu becomes popular among young people, more and more people are beginning to use this platform to share various aspects of their experiences and life insights. How to effectively manage multiple Xiaohongshu accounts has become a key issue. In this article, we will discuss some of the features of Xiaohongshu account management software and explore how to better manage your Xiaohongshu account. As social media grows, many people find themselves needing to manage multiple social accounts. This is also a challenge for Xiaohongshu users. Some Xiaohongshu account management software can help users manage multiple accounts more easily, including automatic content publishing, scheduled publishing, data analysis and other functions. Through these tools, users can manage their accounts more efficiently and increase their account exposure and attention. In addition, Xiaohongshu account management software has

PHP Tips: Quickly implement the function of returning to the previous page. In web development, we often encounter the need to implement the function of returning to the previous page. Such operations can improve the user experience and make it easier for users to navigate between web pages. In PHP, we can achieve this function through some simple code. This article will introduce how to quickly implement the function of returning to the previous page and provide specific PHP code examples. In PHP, we can use $_SERVER['HTTP_REFERER'] to get the URL of the previous page
