如何在 Laravel 5.2 中使用不同的数据库表列名登录?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35692506/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get login with different database table column name in Laravel 5.2?
提问by Akshay Vaghasiya
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
.
我必须在 Laravel 5.2 中实现登录功能。我已经使用官方 Laravel 文档成功地做到了这一点,只是我不知道如何使用不同的数据库表列名称来验证用户身份,即st_username
和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.
我在互联网上搜索了线索,但无济于事。我不知道我需要使用哪个类(例如,使用 Illuminate ......)进行身份验证。如果有人知道答案,请告诉我。
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 App\Http\Controllers\Auth;
use App\User;
use Validator;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
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
配置/auth.php
return [
'defaults' => [
'guard' => 'web',
'passwords' => 'users',
],
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'token',
'provider' => 'users',
],
],
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\User::class,
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
'passwords' => [
'users' => [
'provider' => 'users',
'email' => 'auth.emails.password',
'table' => 'password_resets',
'expire' => 60,
],
],
];
采纳答案by user3632055
I searched a lot how to customize Laravel 5.2authorisation form and this is what is working for me 100%. Here is from bottom to top solution.
我搜索了很多如何自定义Laravel 5.2授权表单,这 100% 对我有用。这是从下到上的解决方案。
This solution is originally from here: https://laracasts.com/discuss/channels/laravel/replacing-the-laravel-authentication-with-a-custom-authentication
此解决方案最初来自此处: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
我的网络应用程序适用于 DJ,因此我的自定义列名称带有“dj_”,例如名称是 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 App\Providers\CustomAuthProvider::class, ... ],
Create CustomAuthProvider.php inside folder app\Providers
namespace App\Providers; use Illuminate\Support\Facades\Auth; use App\Providers\CustomUserProvider; use Illuminate\Support\ServiceProvider; class CustomAuthProvider extends ServiceProvider { /** * Bootstrap the application services. * * @return void */ public function boot() { Auth::provider('custom', function($app, array $config) { // Return an instance of Illuminate\Contracts\Auth\UserProvider... return new CustomUserProvider($app['custom.connection']); }); } /** * Register the application services. * * @return void */ public function register() { // } }
Create CustomUserProvider.php also inside folder app\Providers
<?php namespace App\Providers; use App\User; use Carbon\Carbon; use Illuminate\Auth\GenericUser; use Illuminate\Contracts\Auth\Authenticatable; use Illuminate\Contracts\Auth\UserProvider; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Log; class CustomUserProvider implements UserProvider { /** * Retrieve a user by their unique identifier. * * @param mixed $identifier * @return \Illuminate\Contracts\Auth\Authenticatable|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 \Illuminate\Contracts\Auth\Authenticatable|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 \Illuminate\Contracts\Auth\Authenticatable $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 \Illuminate\Contracts\Auth\Authenticatable|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 \Illuminate\Contracts\Auth\Authenticatable $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 Illuminate\Foundation\Auth\User.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 !!!
配置/auth.php
// change this 'driver' => 'eloquent', // to this 'driver' => 'custom',
在 config/app.php 中,将您的自定义提供程序添加到列表中...
'providers' => [ ... // add this on bottom of other providers App\Providers\CustomAuthProvider::class, ... ],
在文件夹 app\Providers 中创建 CustomAuthProvider.php
namespace App\Providers; use Illuminate\Support\Facades\Auth; use App\Providers\CustomUserProvider; use Illuminate\Support\ServiceProvider; class CustomAuthProvider extends ServiceProvider { /** * Bootstrap the application services. * * @return void */ public function boot() { Auth::provider('custom', function($app, array $config) { // Return an instance of Illuminate\Contracts\Auth\UserProvider... return new CustomUserProvider($app['custom.connection']); }); } /** * Register the application services. * * @return void */ public function register() { // } }
在文件夹 app\Providers 中也创建 CustomUserProvider.php
<?php namespace App\Providers; use App\User; use Carbon\Carbon; use Illuminate\Auth\GenericUser; use Illuminate\Contracts\Auth\Authenticatable; use Illuminate\Contracts\Auth\UserProvider; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Log; class CustomUserProvider implements UserProvider { /** * Retrieve a user by their unique identifier. * * @param mixed $identifier * @return \Illuminate\Contracts\Auth\Authenticatable|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 \Illuminate\Contracts\Auth\Authenticatable|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 \Illuminate\Contracts\Auth\Authenticatable $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 \Illuminate\Contracts\Auth\Authenticatable|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 \Illuminate\Contracts\Auth\Authenticatable $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; } }
在 App/Http/Controllers/Auth/AuthController.php 中,将所有 'name' 更改为 'dj_name' 并添加自定义字段(如果有)...您也可以将 'email' 更改为您的电子邮件列名称
在 Illuminate\Foundation\Auth\User.php 添加
protected $table = 'djs'; protected $primaryKey = 'dj_id';
在 App/User.php 中,将“name”更改为“dj_name”并添加您的自定义字段。要将“密码”列更改为您的自定义列名称,请添加
public function getAuthPassword(){ return $this->custom_password_column_name; }
现在后端都完成了,所以你只需要更改布局 login.blade.php、register.blade.php、app.blade.php...这里你只需要将 'name' 更改为 'dj_name'、email 或您的自定义字段... !!! 密码字段需要保留命名密码!!!
Also, to make unique email validation change AuthController.php
此外,要进行独特的电子邮件验证更改 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 Illuminate\Database\Eloquent\Model.php
此外,如果您想自定义 created_at 和 updated_at 字段,请更改 Illuminate\Database\Eloquent\Model.php 中的全局变量
const CREATED_AT = 'dj_created_at';
const UPDATED_AT = 'dj_updated_at';
回答by Lars Schinkel
A custom Auth::attempt() doesn't work for me by changing the model in auth.php like this:
通过像这样更改 auth.php 中的模型,自定义 Auth::attempt() 对我不起作用:
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Person::class,
],
],
If I try to authenticate a Person via custom column names in Auth::attempt:
如果我尝试通过 Auth::attempt 中的自定义列名称对 Person 进行身份验证:
if (Auth::attempt(['persUsername' => $request->user, 'persPassword' => $request->pass])) {
return redirect()->intended('/');
}
I get the same error:
我犯了同样的错误:
ErrorException in EloquentUserProvider.php line 112: Undefined index: password
EloquentUserProvider.php 第 112 行中的 ErrorException:未定义索引:密码
But I can authenticate a Person like this:
但我可以像这样验证一个人:
$person = Person
::where('persUsername', $request->user)
->where('persPassword', $request->pass)
->first();
if (! is_null($person)) {
if ($person->persUsername === $request->user && $person->persPassword === $request->pass) {
Auth::login($person, false);
return redirect()->intended('/');
}
}
But that's not the way it should be, I guess.
但我想这不是应该的方式。
In the mentioned File (EloquentUserProvider.php), I see 'password' is hardcoded.
在提到的文件 (EloquentUserProvider.php) 中,我看到“密码”是硬编码的。
public function retrieveByCredentials(array $credentials)
{
$query = $this->createModel()->newQuery();
foreach ($credentials as $key => $value) {
if (! Str::contains($key, 'password')) {
$query->where($key, $value);
}
}
return $query->first();
}
public function validateCredentials(UserContract $user, array $credentials)
{
$plain = $credentials['password'];
return $this->hasher->check($plain, $user->getAuthPassword());
}
So there is actually no way to use a custom column name for passwords the easy way?
那么实际上没有办法以简单的方式使用自定义列名作为密码吗?
回答by Emeka Mbah
This is easy simply use the desired column names in Auth::attempt()/method like so:
这很简单,只需在 Auth::attempt()/method 中使用所需的列名,如下所示:
if (Auth::attempt(['st_username' =>$username,'st_password' => $password])) {
// Authentication passed...
return redirect()>intended('dashboard');
}
Updated:If you also wish to change default authentication table which is users
by default or change the model name or path App\User
by default, you can find these settings in config\auth.php
更新:如果您还希望更改默认的默认身份验证表users
或默认更改模型名称或路径App\User
,您可以在config\auth.php
/*
|--------------------------------------------------------------------------
| Authentication Table
|--------------------------------------------------------------------------
|
| When using the "Database" authentication driver, we need to know which
| table should be used to retrieve your users. We have chosen a basic
| default value but you may easily change it to any table you like.
|
*/
//'table' => 'users',
'table' => 'new_tables_for_authentication',
/*
|--------------------------------------------------------------------------
| Authentication Model
|--------------------------------------------------------------------------
|
| When using the "Eloquent" authentication driver, we need to know which
| Eloquent model should be used to retrieve your users. Of course, it
| is often just the "User" model but you may use whatever you like.
|
*/
//'model' => App\User::class,
'model' => App\Models\User::class,