Home > Backend Development > PHP Tutorial > Laravel 实现多字段登录

Laravel 实现多字段登录

WBOY
Release: 2016-06-23 13:16:34
Original
1113 people have browsed it

现在很多网站都提供了这样的功能,用户可以通过邮箱、手机号或者昵称来登录网站,下面是在 Laravel (以 5.1 为例)中实现该功能的方式。

下面三种方法基本原理都是相同的。

1. 方法一

使用 Laravel 自带认证系统,修改 /app/Http/Controllers/Auth/AuthController.php 文件,重写方法(原方法所在文件 /vendor/laravel/framework/src/Illuminate/Foundation/Auth/AuthenticatesUsers.php):

namespace App\Http\Controllers\Auth;......use Illuminate\Http\Request; // 增加该行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'),        ];    }}
Copy after login

2. 方法二

修改 /app/Http/Controllers/Auth/AuthController.php 文件,这也是使用 Laravel 自带认证系统的一种方法。

namespace App\Http\Controllers\Auth;......use Illuminate\Http\Request; // 增加该行class AuthController extends Controller{    // 修改这里    use AuthenticatesAndRegistersUsers, ThrottlesLogins {        AuthenticatesAndRegistersUsers::postLogin as laravelPostLogin;    }    ......    // 增加方法    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);    }}
Copy after login

3. 方法三

重写登录功能

LoginRequest.php:

public function rules(){    return [       'login' => 'required',       'password' => 'required'    ];}
Copy after login

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.',    ]);}
Copy after login

该篇属于专题:《Laravel小技巧》

  • 上一篇: 《 Laravel更改登录时使用的默认字段名称email》
Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template