在 Laravel Auth() 中通过电子邮件/电话号码登录
Posted
技术标签:
【中文标题】在 Laravel Auth() 中通过电子邮件/电话号码登录【英文标题】:Login by Email/Phone number in Laravel Auth() 【发布时间】:2017-04-06 03:21:18 【问题描述】:我正在使用
Route::auth();
用于在 Laravel 中进行用户登录。 有多个电话链接到一个用户并保存在 table:phones 中。 表是 用户 : id,email,password 手机:id,user_id,phone_number
如何让用户同时使用电子邮件/电话和密码登录
【问题讨论】:
您可以验证数据库中的详细信息,然后可以使用 Auth::loginUsingId($user_id);登录用户 感谢@geekbro。试试这个 你试过用Auth::basic('username')
吗?
首先我正在检查数据库,如果用户凭据正确,则使用 Auth::loginUsingId($user_id);然后重定向到仪表板
【参考方案1】:
在App\Traits\Auth
中,创建一个名为LoginUser.php
的文件。
<?php
namespace App\Traits\Auth;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
trait LoginUser
/**
* Handle a Authenticates the User.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function login(Request $request)
$this->validateLogin($request);
if ($this->attemptLogin($request))
return $this->successfulLogin($request);
return $this->failedLogin($request);
/**
* Validate the user login request.
*
* @param \Illuminate\Http\Request $request
* @return void
*/
protected function validateLogin(Request $request)
$this->validate($request, [
'username' => 'required',
'password' => 'required',
]);
/**
* Attempt to log the user into the application.
*
* @param \Illuminate\Http\Request $request
* @return bool
*/
protected function attemptLogin(Request $request)
//Try with email AND username fields
if (Auth::attempt([
'phone' => $request['username'],
'password' => $request['password']
],$request->has('remember'))
|| Auth::attempt([
'email' => $request['username'],
'password' => $request['password']
],$request->has('remember')))
return true;
return false;
/**
* This is executed when the user successfully logs in
*
* @var Request $request
* @return Reponse
*/
protected function successfulLogin(Request $request)
return redirect($this->redirectTo);
/**
* This is executed when the user fails to log in
*
* @var Request $request
* @return Reponse
*/
protected function failedLogin(Request $request)
return redirect()->back()->withErrors(['password' => 'You entered the wrong username or password']);
然后在
App\Http\Controllers\Auth
重写(或创建)LoginController.php
并粘贴
<?php
namespace App\Http\Controllers\Auth;
use App\Traits\Auth\LoginUser;
use App\Http\Controllers\Controller;
class LoginController extends Controller
use LoginUser;
/**
* Where to redirect users after registration.
*
* @var string | URL
*/
protected $redirectTo = '/mPanel';
/**
* Displays login page
*
* @return \Illuminate\Http\Response
*/
public function show()
return response()->view('LOGIN PAGE HERE');
最后在你的路由文件中,添加这些路由:
Route::get('login', 'Auth\LoginController@show');
Route::post('login', 'Auth\LoginController@login');
【讨论】:
以上是关于在 Laravel Auth() 中通过电子邮件/电话号码登录的主要内容,如果未能解决你的问题,请参考以下文章