Home Backend Development PHP Tutorial About how to implement multi-field login in Laravel5.4

About how to implement multi-field login in Laravel5.4

Jun 13, 2018 pm 04:36 PM
laravel laravel5.4 User login

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([&#39;email&#39; => $email, &#39;password&#39; => $password])) {
   // Authentication passed...
   return redirect()->intended(&#39;dashboard&#39;);
  }
 }
}
Copy after login

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&#39;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);
 }
Copy after login

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(&#39;remember&#39;)
  );
 }
Copy after login

After the LoginController is rewritten:

public function attemptLogin(Request $request)
 {
  $username = $request->input(&#39;username&#39;);
  $password = $request->input(&#39;password&#39;);

  // 验证用户名登录方式
  $usernameLogin = $this->guard()->attempt(
   [&#39;username&#39; => $username, &#39;password&#39; => $password], $request->has(&#39;remember&#39;)
  );
  if ($usernameLogin) {
   return true;
  }

  // 验证手机号登录方式
  $mobileLogin = $this->guard()->attempt(
   [&#39;mobile&#39; => $username, &#39;password&#39; => $password], $request->has(&#39;remember&#39;)
  );
  if ($mobileLogin) {
   return true;
  }

  // 验证邮箱登录方式
  $emailLogin = $this->guard()->attempt(
   [&#39;email&#39; => $username, &#39;password&#39; => $password], $request->has(&#39;remember&#39;)
  );
  if ($emailLogin) {
   return true;
  }

  return false;
 }
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP vs. Flutter: The best choice for mobile development PHP vs. Flutter: The best choice for mobile development May 06, 2024 pm 10:45 PM

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.

How to use object-relational mapping (ORM) in PHP to simplify database operations? How to use object-relational mapping (ORM) in PHP to simplify database operations? May 07, 2024 am 08:39 AM

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.

Analysis of the advantages and disadvantages of PHP unit testing tools Analysis of the advantages and disadvantages of PHP unit testing tools May 06, 2024 pm 10:51 PM

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 - Artisan Commands Aug 27, 2024 am 10:51 AM

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 ?

Comparison of the latest versions of Laravel and CodeIgniter Comparison of the latest versions of Laravel and CodeIgniter Jun 05, 2024 pm 05:29 PM

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.

How do the data processing capabilities in Laravel and CodeIgniter compare? How do the data processing capabilities in Laravel and CodeIgniter compare? Jun 01, 2024 pm 01:34 PM

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 code unit testing and integration testing PHP code unit testing and integration testing May 07, 2024 am 08:00 AM

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.

Which one is more beginner-friendly, Laravel or CodeIgniter? Which one is more beginner-friendly, Laravel or CodeIgniter? Jun 05, 2024 pm 07:50 PM

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.

See all articles