如何将自定义表和自定义模型连接到laravel的auth :: attempt

时间:2019-01-27 05:43:47

标签: laravel authentication model customization

我有一个名为“ prj_user”的表,并且用户数据存储在该表中

表的字段写在下面

CREATE TABLE IF NOT EXISTS `prj_users` (
`usr_user_id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`usr_firstname` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`usr_lastname` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`usr_email` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`usr_pass` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`usr_created_at` timestamp NULL DEFAULT NULL,
`usr_updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`usr_user_id`),
) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

对于此表,我在“ app / models / UserCustom.php”处创建了一个名为UserCustom.php的模型,并且还创建了一个名为“ Models”的文件夹,所有项目的模型都将保存在该文件夹

以下代码是UserCustom.php的模型代码。


namespace App\Models;


use Illuminate\Database\Eloquent\Model;

class UserCustom extends Model
{
  public $table='prj_users';
  public $primaryKey='usr_user_id';

  const CREATED_AT='usr_created_at';
  const UPDATED_AT='usr_updated_at';

  protected $fillable = [
    'usr_user_id',
    'usr_firstname',
    'usr_lastname',
    'usr_email',
    'usr_pass',
    'usr_lastname',
    'usr_created_at',
    'usr_updated_at',
  ];

}

我想将auth :: attempt和其他类方法auth连接到该表和此模型

我不想将“模型用户”和“表用户”用作laravel的默认值。

可以在此级别自定义Laravel吗?

有可能吗?

2 个答案:

答案 0 :(得分:0)

在config \ auth.php中, 创建新的后卫为

'customguard' => [
        'driver' => 'session',
        'provider' => 'userscustom',
    ],

,并创建提供者为

'userscustom' => [
        'driver' => 'eloquent',
        'model' => App\Models\UserCustom::class,
    ],

,然后将默认警卫更改为“ cutomguard”。请记住,还要对密码进行相应的更改。

答案 1 :(得分:0)

我将以下代码添加到文件config / auth.php

<?php
'guards' => [

'usercustom' => [
    'driver' => 'session',
    'provider' => 'userCustomProvider',
  ],
],

'providers' => [

  'userCustomProvider' => [
    'driver' => 'eloquent',
    'model' => App\Models\UserCustom::class,
  ],

],
?>

然后我在Providers floder中创建了两个类CustomAuthProvider和CustomUserProvider

<?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()
  {
    $this->app['auth']->extend('usercustom',function()
    {
      return new CustomUserProvider();
    });
  }

  /**
   * Register the application services.
   *
   * @return void
   */
  public function register()
  {
    //
  }
}


<?php

namespace App\Providers;
use App\Models\UserCustom;
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 = UserCustom::where('usr_user_id','=',$identifier);

    if($qry->count() >0)
    {
      $user = $qry->select('usr_user_id', 'usr_firstname', 'usr_last_name', 'usr_email', 'usr_pass')->first();

      $attributes = array(
        'usr_user_id' => $user->usr_user_id,
        'usr_firstname' => $user->usr_firstname,
        'usr_last_name' => $user->usr_last_name,
        'usr_email' => $user->usr_email,
        'usr_pass' => $user->usr_pass,
      );

      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 = UserCustom::where('usr_user_id','=',$identifier);

    if($qry->count() >0)
    {
      $user = $qry->select('usr_user_id', 'usr_firstname', 'usr_last_name', 'usr_email', 'usr_pass')->first();

      $attributes = array(
        'usr_user_id' => $user->usr_user_id,
        'usr_firstname' => $user->usr_firstname,
        'usr_last_name' => $user->usr_last_name,
        'usr_email' => $user->usr_email,
        'usr_pass' => $user->usr_pass,
      );

      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 = UserCustom::where('usr_email','=',$credentials['usr_email']);

    if($qry->count() > 0)
    {
      $user = $qry->select('usr_user_id','usr_email','usr_pass')->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['usr_email'] && Hash::check($credentials['usr_pass'], $user->getAuthPassword()))//$user->getAuthPassword() == md5($credentials['password'].\Config::get('constants.SALT')))
    {


      //$user->last_login_time = Carbon::now();
      $user->save();

      return true;
    }
    return false;


  }
}

然后我走了两条路

Route::get('user/login','UserController@loginForm');
Route::post('user/login','UserController@loginCheck');
<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Auth;
use Illuminate\Http\Request;

class UserController extends Controller
{


    public function loginForm () {
      return view('login');
    }

    public function loginCheck (Request $request) {

      $credentials=array([
        'usr_email'=> $request->email,
        'usr_pass'=>$request->password
      ]);
     if (Auth::guard('usercustom')->attempt($credentials)){
       echo "1";
     }else {
       echo "0";
     }

    }


}

我以主题为主题编写了类模型 到达Auth :: guard时,出现以下错误

QLSTATE [42S22]:找不到列:1054'where子句'中的未知列'0'(SQL:在(test@test.com,123456)中从tua_users的{​​{1}}中选择*限制1) 以前的例外 SQLSTATE [42S22]:找不到列:1054“ where子句”(42S22)中的未知列“ 0”

我在互联网上搜索过多,但无法解决问题。 问题出在表的字段上。laravel默认将电子邮件和密码更改为“ usr_email”和“ usr_pass”。我也更改了表和模型