如何在 Laravel 5.2 中使用不同的数据库表列名登录?
我必须在 Laravel 5.2 中实现登录功能.我已经使用官方 Laravel 文档成功地做到了这一点,只是我不知道如何使用不同的数据库表列名称来验证用户,即 st_username
和 st_password
.
我已经在互联网上搜索了线索,但无济于事.我不知道我需要使用哪个类(例如,使用 Illuminate ......)进行身份验证.如果有人知道答案,请告诉我.
这是我的代码:
登录查看
@extends('layouts.app')@section('内容')<div class="contact-bg2"><div class="容器"><div class="booking"><h3>登录</h3><div class="col-md-4 booking-form" style="margin: 0 33%;"><form method="post" action="{{ url('/login') }}">{!!csrf_field() !!}<h5>用户名</h5><input type="text" name="username" value="abcuser"><h5>密码</h5><input type="password" name="password" value="abcpass"><input type="submit" value="登录"><输入类型=重置"值=重置"></表单><div></div>@endsection
授权控制器
命名空间 AppHttpControllersAuth;使用 AppUser;使用验证器;使用 AppHttpControllersController;使用 IlluminateFoundationAuthThrottlesLogins;使用 IlluminateFoundationAuthAuthenticatesAndRegistersUsers;类 AuthController 扩展控制器{使用 AuthenticatesAndRegistersUsers、ThrottlesLogins;受保护的 $redirectTo = '/home';公共函数 __construct(){$this->middleware('guest', ['except' => 'logout']);$this->username = 'st_username';$this->password = 'st_password';}受保护的函数验证器(数组 $data){返回 Validator::make($data, ['名称' =>'需要|最大:255','电子邮件' =>'required|email|max:255|unique:users','密码' =>'需要|确认|分钟:6',]);}
路由文件
Route::get('/', function () {返回视图('索引');});Route::group(['middleware' => 'web'], function () {路线::认证();Route::get('/home', 'HomeController@index');});
config/auth.php
返回 ['默认' =>['守卫' =>'网络','密码' =>'用户',],'守卫' =>['网络' =>['司机' =>'会议','提供者' =>'用户',],'api' =>['司机' =>'令牌','提供者' =>'用户',],],'提供者' =>['用户' =>['司机' =>'雄辩','模型' =>应用用户::类,],//'用户' =>[//'司机' =>'数据库',//'表' =>'用户',//],],'密码' =>['用户' =>['提供者' =>'用户','电子邮件' =>'auth.emails.password','表' =>'密码重置','过期' =>60,],],];
解决方案 我搜索了很多如何自定义 Laravel 5.2 授权表单,这 100% 对我有用.这是从下到上的解决方案.
此解决方案最初来自此处:https://laracasts.com/discuss/channels/laravel/replacing-the-laravel-authentication-with-a-custom-authentication
但我必须进行一些更改才能使其正常工作.
我的网络应用程序是为 DJ 而设计的,所以我的自定义列名称带有dj_",例如名称是 dj_name
config/auth.php
//改变这个'司机' =>'雄辩',//到这个'司机' =>'风俗',
在 config/app.php 中将您的自定义提供程序添加到列表中...
'providers' =>[...//将此添加到其他提供者的底部AppProvidersCustomAuthProvider::class,...],
在文件夹 appProviders 中创建 CustomAuthProvider.php
命名空间 AppProviders;使用 IlluminateSupportFacadesAuth;使用 AppProvidersCustomUserProvider;使用 IlluminateSupportServiceProvider;类 CustomAuthProvider 扩展了 ServiceProvider {/*** 引导应用程序服务.** @return 无效*/公共函数引导(){Auth::provider('custom', function($app, array $config) {//返回 IlluminateContractsAuthUserProvider 的一个实例...return new CustomUserProvider($app['custom.connection']);});}/*** 注册应用服务.** @return 无效*/公共函数 register(){//}}
也在文件夹 appProviders 中创建 CustomUserProvider.php
count()>0){$user = $qry->select('dj_id', 'dj_name', 'first_name', 'last_name', 'email', 'password')->first();$属性=数组('id' =>$user->dj_id,'dj_name' =>$user->dj_name,'密码' =>$用户->密码,'电子邮件' =>$用户->电子邮件,'名称' =>$user->first_name .' ' .$user->last_name,);返回 $user;}返回空;}/*** 通过用户的唯一标识符和记住我"令牌检索用户.** @param 混合 $identifier* @param 字符串 $token* @return IlluminateContractsAuthAuthenticatable|null*/公共函数retrieveByToken($identifier, $token){//TODO:实现retrieveByToken() 方法.$qry = User::where('dj_id','=',$identifier)->where('remember_token','=',$token);if($qry->count()>0){$user = $qry->select('dj_id', 'dj_name', 'first_name', 'last_name', 'email', 'password')->first();$属性=数组('id' =>$user->dj_id,'dj_name' =>$user->dj_name,'密码' =>$用户->密码,'电子邮件' =>$用户->电子邮件,'名称' =>$user->first_name .' ' .$user->last_name,);返回 $user;}返回空;}/*** 更新存储中给定用户的记住我"令牌.** @param IlluminateContractsAuthAuthenticatable $user* @param 字符串 $token* @return 无效*/公共函数 updateRememberToken(Authenticatable $user, $token){//TODO: 实现 updateRememberToken() 方法.$user->setRememberToken($token);$user->save();}/*** 通过给定的凭据检索用户.** @param 数组 $credentials* @return IlluminateContractsAuthAuthenticatable|null*/公共函数retrieveByCredentials(array $credentials){//TODO: 实现retrieveByCredentials() 方法.$qry = User::where('email','=',$credentials['email']);if($qry->count()>0){$user = $qry->select('dj_id','dj_name','email','password')->first();返回 $user;}返回空;}/*** 根据给定的凭据验证用户.** @param IlluminateContractsAuthAuthenticatable $user* @param 数组 $credentials* @return 布尔值*/公共函数 validateCredentials(Authenticatable $user, array $credentials){//TODO: 实现 validateCredentials() 方法.//我们假设如果检索到用户,那就很好//不同于原始答案if($user->email == $credentials['email'] && Hash::check($credentials['password'], $user->getAuthPassword()))//$user->;getAuthPassword() == md5($credentials['password'].Config::get('constants.SALT'))){//$user->last_login_time = Carbon::now();$user->save();返回真;}返回假;}}
在 App/Http/Controllers/Auth/AuthController.php 中更改所有'name' 到 'dj_name' 并添加您的自定义字段(如果有)...您也可以将 'email' 更改为您的电子邮件列名称
在 IlluminateFoundationAuthUser.php 中添加
protected $table = 'djs';受保护的 $primaryKey = 'dj_id';
在 App/User.php 中,将name"更改为dj_name"并添加您的自定义字段.要将密码"列更改为您的自定义列名称,请添加
公共函数getAuthPassword(){返回 $this->custom_password_column_name;}
现在后端都完成了,所以你只需要改变布局 login.blade.php, register.blade.php, app.blade.php...这里你只需要把 'name' 改为 'dj_name'、电子邮件或您的自定义字段...<强>!!!密码字段需要保留命名密码!!!
此外,要进行唯一的电子邮件验证更改 AuthController.php
'custom_email_field' =>'required|email|max:255|unique:users',到'custom_email_field' =>'必需|电子邮件|最大:255|唯一:custom_table_name',
此外,如果您想自定义 created_at 和 updated_at 字段,请更改 IlluminateDatabaseEloquentModel.php 中的全局变量
const CREATED_AT = 'dj_created_at';const UPDATED_AT = 'dj_updated_at';
I have to implement login functionality in Laravel 5.2. I have successfully done so using the official Laravel documentation except that I do not know how to authenticate the user using different database table column names, namely st_username
and st_password
.
I have searched the Internet for clues but to no avail. I don't know which class I need to use (like, use Illuminate.......) for Auth. If any one knows the answer, please let me know.
Here is my code:
Login View
@extends('layouts.app')
@section('content')
<div class="contact-bg2">
<div class="container">
<div class="booking">
<h3>Login</h3>
<div class="col-md-4 booking-form" style="margin: 0 33%;">
<form method="post" action="{{ url('/login') }}">
{!! csrf_field() !!}
<h5>USERNAME</h5>
<input type="text" name="username" value="abcuser">
<h5>PASSWORD</h5>
<input type="password" name="password" value="abcpass">
<input type="submit" value="Login">
<input type="reset" value="Reset">
</form>
</div>
</div>
</div>
</div>
<div></div>
@endsection
AuthController
namespace AppHttpControllersAuth;
use AppUser;
use Validator;
use AppHttpControllersController;
use IlluminateFoundationAuthThrottlesLogins;
use IlluminateFoundationAuthAuthenticatesAndRegistersUsers;
class AuthController extends Controller
{
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
protected $redirectTo = '/home';
public function __construct()
{
$this->middleware('guest', ['except' => 'logout']);
$this->username = 'st_username';
$this->password = 'st_password';
}
protected function validator(array $data)
{
return Validator::make($data, [
'name' => 'required|max:255',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|confirmed|min:6',
]);
}
Route File
Route::get('/', function () {
return view('index');
});
Route::group(['middleware' => 'web'], function () {
Route::auth();
Route::get('/home', 'HomeController@index');
});
config/auth.php
return [
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => AppUser::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
'passwords' => [
'users' => [
'provider' => 'users',
'email' => 'auth.emails.password',
'table' => 'password_resets',
'expire' => 60,
],
],
];
解决方案
I searched a lot how to customize Laravel 5.2 authorisation form and this is what is working for me 100%. Here is from bottom to top solution.
This solution is originally from here: https://laracasts.com/discuss/channels/laravel/replacing-the-laravel-authentication-with-a-custom-authentication
but i had to make couple changes to make it work.
My web app is for the DJs so my custom column names are with 'dj_', for example name is dj_name
config/auth.php
// change this 'driver' => 'eloquent', // to this 'driver' => 'custom',
in config/app.php add your custom provider to the list ...
'providers' => [ ... // add this on bottom of other providers AppProvidersCustomAuthProvider::class, ... ],
Create CustomAuthProvider.php inside folder appProviders
namespace AppProviders; use IlluminateSupportFacadesAuth; use AppProvidersCustomUserProvider; use IlluminateSupportServiceProvider; class CustomAuthProvider extends ServiceProvider { /** * Bootstrap the application services. * * @return void */ public function boot() { Auth::provider('custom', function($app, array $config) { // Return an instance of IlluminateContractsAuthUserProvider... return new CustomUserProvider($app['custom.connection']); }); } /** * Register the application services. * * @return void */ public function register() { // } }
Create CustomUserProvider.php also inside folder appProviders
<?php namespace AppProviders; use AppUser; use CarbonCarbon; use IlluminateAuthGenericUser; use IlluminateContractsAuthAuthenticatable; use IlluminateContractsAuthUserProvider; use IlluminateSupportFacadesHash; use IlluminateSupportFacadesLog; class CustomUserProvider implements UserProvider { /** * Retrieve a user by their unique identifier. * * @param mixed $identifier * @return IlluminateContractsAuthAuthenticatable|null */ public function retrieveById($identifier) { // TODO: Implement retrieveById() method. $qry = User::where('dj_id','=',$identifier); if($qry->count() >0) { $user = $qry->select('dj_id', 'dj_name', 'first_name', 'last_name', 'email', 'password')->first(); $attributes = array( 'id' => $user->dj_id, 'dj_name' => $user->dj_name, 'password' => $user->password, 'email' => $user->email, 'name' => $user->first_name . ' ' . $user->last_name, ); return $user; } return null; } /** * Retrieve a user by by their unique identifier and "remember me" token. * * @param mixed $identifier * @param string $token * @return IlluminateContractsAuthAuthenticatable|null */ public function retrieveByToken($identifier, $token) { // TODO: Implement retrieveByToken() method. $qry = User::where('dj_id','=',$identifier)->where('remember_token','=',$token); if($qry->count() >0) { $user = $qry->select('dj_id', 'dj_name', 'first_name', 'last_name', 'email', 'password')->first(); $attributes = array( 'id' => $user->dj_id, 'dj_name' => $user->dj_name, 'password' => $user->password, 'email' => $user->email, 'name' => $user->first_name . ' ' . $user->last_name, ); return $user; } return null; } /** * Update the "remember me" token for the given user in storage. * * @param IlluminateContractsAuthAuthenticatable $user * @param string $token * @return void */ public function updateRememberToken(Authenticatable $user, $token) { // TODO: Implement updateRememberToken() method. $user->setRememberToken($token); $user->save(); } /** * Retrieve a user by the given credentials. * * @param array $credentials * @return IlluminateContractsAuthAuthenticatable|null */ public function retrieveByCredentials(array $credentials) { // TODO: Implement retrieveByCredentials() method. $qry = User::where('email','=',$credentials['email']); if($qry->count() > 0) { $user = $qry->select('dj_id','dj_name','email','password')->first(); return $user; } return null; } /** * Validate a user against the given credentials. * * @param IlluminateContractsAuthAuthenticatable $user * @param array $credentials * @return bool */ public function validateCredentials(Authenticatable $user, array $credentials) { // TODO: Implement validateCredentials() method. // we'll assume if a user was retrieved, it's good // DIFFERENT THAN ORIGINAL ANSWER if($user->email == $credentials['email'] && Hash::check($credentials['password'], $user->getAuthPassword()))//$user->getAuthPassword() == md5($credentials['password'].Config::get('constants.SALT'))) { //$user->last_login_time = Carbon::now(); $user->save(); return true; } return false; } }
in App/Http/Controllers/Auth/AuthController.php change all 'name' to 'dj_name' and add your custom fields if you have them...you can also change 'email' to your email column name
In IlluminateFoundationAuthUser.php add
protected $table = 'djs'; protected $primaryKey = 'dj_id';
In App/User.php change 'name' to 'dj_name' and add your custom fields. For changing 'password' column to your custom column name add
public function getAuthPassword(){ return $this->custom_password_column_name; }
Now backend is all done, so you only have to change layouts login.blade.php, register.blade.php, app.blade.php...here you only have to change 'name' to 'dj_name', email, or your custom fields... !!! password field NEEDS to stay named password !!!
Also, to make unique email validation change AuthController.php
'custom_email_field' => 'required|email|max:255|unique:users',
to
'custom_email_field' => 'required|email|max:255|unique:custom_table_name',
Also, if you want to make custom created_at an updated_at fields change global variables in IlluminateDatabaseEloquentModel.php
const CREATED_AT = 'dj_created_at';
const UPDATED_AT = 'dj_updated_at';
相关文章