数据库注意事项
如果你想在你的 laravel 应用程序上使用你的自定义数据库,你只需要为你的数据库的每个表创建一个模型,并设置表名、主键和可填充属性。
更多信息在这里Defining Models
使用自定义用户和传递字段进行身份验证
如果您运行了命令php artisan make:auth,但您想使用另一个表或字段而不是默认用户并在不破坏创建的身份验证功能的情况下通过,您必须按照下面列出的步骤让 laravel 知道它:
首先:为要用于身份验证的表创建一个模型。为此,请运行命令 php artisan make:model FooUserTable,其中 'FooUser' 是您的表的名称。
接下来,您必须在模型上设置您的表名、主键和可填充字段,如下所示:
class FooUser extends Authenticatable{
protected $table = 'FooUser';
protected $primaryKey = 'foo_id_user'; // Place here the name of the id of your table
protected $fillable = [ // Insert here all the fillable fields of your users table
'field1',
'field2',
...
];
}
请注意,模型现在扩展自 Authenticatable 而不是模型,这是 Illuminate\Foundation\Auth\User 类的别名。为了使其正常工作,只需将use Illuminate\Foundation\Auth\User as Authenticatable 放在文件顶部即可。
这很重要!:
要使用另一个字段名称作为密码,请将函数 getAuthPassword 放入用户表的模型中,如下所示:
public function getAuthPassword(){
return $this->myPasswordField; // myPasswordField is the field on your users table for password
}
现在您已为下一步准备好所有模型。
第二:在文件config > auth.php你要找到providers数组,把模型属性值改成你的模型类名,例如:
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\FooUser::class, // Place here the name of your model
],
],
为下一步做好准备。
第三: 现在您必须找到默认 Laravel Auth 的控制器,位于 app > http > controllers > auth > LoginController.php 中,然后在类中添加一个名为 username 的函数,该函数返回用于身份验证操作的用户名,如下所示:
class LoginController extends Controller{
..... // don't change other functions
public function username(){ // add the function username
return 'YourUsernameField';
}
}
Blade登录模板注意:在你的登录blade模板中,用户名输入名称要改成新的,密码字段名称必须还是password,因为laravel使用了用于验证,但在内部它将使用您的自定义密码字段名称。
仅此而已。希望对您有所帮助。
注意:切勿将文件编辑到供应商文件夹中!
有关更多信息,请阅读Manually Authenticating Users 部分的文档
所有这些都在 Laravel 5.4 和 5.7 版本上进行了测试。