About how to implement multi-field login in Laravel5.4
This article mainly introduces the method of implementing multi-field login in Laravel5.4. It has certain reference value. Now I share it with you. Friends in need can refer to it.
I encountered it at work recently One requirement is 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 to you the implementation of multi-field login based on Laravel5.4. Friends who need it can refer to the relevant information about the functions. Let’s take a look below.
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
The official documentation of laravel 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 is unsuccessful, continue to use other fields to judge. If it is unsuccessful, it will return fle
Test, which can achieve multi-field login effect
The above is the entire content of this article. I hope it will be useful to everyone. Helpful, please pay attention to the PHP Chinese website for more related content!
Related recommendations:
How to implement SMS registration with Laravel
How to use Laravel to implement scheduled tasks
The above is the detailed content of About how to implement multi-field login 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

AI Hentai Generator
Generate AI Hentai for free.

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

PHP and Flutter are popular technologies for mobile development. Flutter excels in cross-platform capabilities, performance and user interface, and is suitable for applications that require high performance, cross-platform and customized UI. PHP is suitable for server-side applications with lower performance and not cross-platform.

Database operations in PHP are simplified using ORM, which maps objects into relational databases. EloquentORM in Laravel allows you to interact with the database using object-oriented syntax. You can use ORM by defining model classes, using Eloquent methods, or building a blog system in practice.

PHP unit testing tool analysis: PHPUnit: suitable for large projects, provides comprehensive functionality and is easy to install, but may be verbose and slow. PHPUnitWrapper: suitable for small projects, easy to use, optimized for Lumen/Laravel, but has limited functionality, does not provide code coverage analysis, and has limited community support.

Laravel - Artisan Commands - Laravel 5.7 comes with new way of treating and testing new commands. It includes a new feature of testing artisan commands and the demonstration is mentioned below ?

The latest versions of Laravel 9 and CodeIgniter 4 provide updated features and improvements. Laravel9 adopts MVC architecture and provides functions such as database migration, authentication and template engine. CodeIgniter4 uses HMVC architecture to provide routing, ORM and caching. In terms of performance, Laravel9's service provider-based design pattern and CodeIgniter4's lightweight framework give it excellent performance. In practical applications, Laravel9 is suitable for complex projects that require flexibility and powerful functions, while CodeIgniter4 is suitable for rapid development and small applications.

Compare the data processing capabilities of Laravel and CodeIgniter: ORM: Laravel uses EloquentORM, which provides class-object relational mapping, while CodeIgniter uses ActiveRecord to represent the database model as a subclass of PHP classes. Query builder: Laravel has a flexible chained query API, while CodeIgniter’s query builder is simpler and array-based. Data validation: Laravel provides a Validator class that supports custom validation rules, while CodeIgniter has less built-in validation functions and requires manual coding of custom rules. Practical case: User registration example shows Lar

PHP Unit and Integration Testing Guide Unit Testing: Focus on a single unit of code or function and use PHPUnit to create test case classes for verification. Integration testing: Pay attention to how multiple code units work together, and use PHPUnit's setUp() and tearDown() methods to set up and clean up the test environment. Practical case: Use PHPUnit to perform unit and integration testing in Laravel applications, including creating databases, starting servers, and writing test code.

For beginners, CodeIgniter has a gentler learning curve and fewer features, but covers basic needs. Laravel offers a wider feature set but has a slightly steeper learning curve. In terms of performance, both Laravel and CodeIgniter perform well. Laravel has more extensive documentation and active community support, while CodeIgniter is simpler, lightweight, and has strong security features. In the practical case of building a blogging application, Laravel's EloquentORM simplifies data manipulation, while CodeIgniter requires more manual configuration.
