How to get login with column name of database table in Laravel 5.2?

I need to implement login features in Laravel 5.2. I have successfully done this using the official Laraval documentation, except that I do not know how to authenticate the user using the column names of the database table, namely st_username and st_password .

I searched the Internet for tips, but to no avail. I do not know which class I need to use (for example, use Illuminate .......) for Auth. If anyone knows the answer, please let me know.

Here is my code:

Login

 @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

 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, ], ], ]; 
+6
source share
3 answers

I have searched many times how to configure the Laravel 5.2 authorization form, and this is what works for me 100%. Here is from the bottom to the top solution.

This solution comes from here: https://laracasts.com/discuss/channels/laravel/replacing-the-laravel-authentication-with-a-custom-authentication

but I had to make a couple of changes to make it work.

My web application is for DJs, so my own column names have "dj_", for example 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 the CustomAuthProvider.php application inside the \ Providers folder

     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 and inside the app \ Providers folder

     <?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 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 ... you can also change the "email" to the column name of your mailbox

  • In Illuminate \ Foundation \ Auth \ User.php add

     protected $table = 'djs'; protected $primaryKey = 'dj_id'; 
  • In App / User.php, change the name to 'dj_name' and add your custom fields. To change the password column to your own column name, add

     public function getAuthPassword(){ return $this->custom_password_column_name; } 
  • Now the backend is done, so you only need to change the layouts login.blade.php, register.blade.php, app.blade.php ... here you only need to change the name, dj_name ', email or your custom fields ... !!! NEEDS password field to remain with the name password !!!

In addition, to make a unique change to the email validation 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 custom create_at updated_at fields to modify global variables in Illuminate \ Database \ Eloquent \ Model.php

 const CREATED_AT = 'dj_created_at'; const UPDATED_AT = 'dj_updated_at'; 
+3
source

It is easy to just use the names of the desired columns in Auth :: try () / method as follows:

 if (Auth::attempt(['st_username' =>$username,'st_password' => $password])) { // Authentication passed... return redirect()>intended('dashboard'); } 

Updated: If you also want to change the default authentication table, which defaults to users or change the default model name or App\User path, you can find these settings in 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, 
+2
source

Custom Auth :: attempt () does not work for me, changing the model in auth.php as follows:

 'providers' => [ 'users' => [ 'driver' => 'eloquent', 'model' => App\Person::class, ], ], 

If I try to authenticate Faces using custom column names in Auth :: try:

 if (Auth::attempt(['persUsername' => $request->user, 'persPassword' => $request->pass])) { return redirect()->intended('/'); } 

I get the same error:

Error Exception in EloquentUserProvider.php line 112: Undefined index: password

But I can authenticate 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 this is not as it should be, I think.

In the specified file (EloquentUserProvider.php) I see that the "password" is hard-coded.

 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 really is no way to use a custom column name for passwords in a simple way?

+2
source

All Articles