Nar*_*tor 3 laravel eloquent lumen
我目前正在摆弄 Lumen,并使用 eloquent 进行数据库交互。我读过 Eloquent 的文档,其中有关于隐藏属性的解释:
有时您可能希望限制模型数组或 JSON 表示中包含的属性,例如密码。为此,请将 $hidden 属性添加到您的模型中:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = ['password'];
}
Alternatively, you may use the visible property to define a white-list of attributes that should be included in your model's array and JSON representation. All other attributes will be hidden when the model is converted to an array or JSON:
Run Code Online (Sandbox Code Playgroud)
我不明白这有什么含义。如果我有一个插入密码的查询,我应该隐藏它吗?或者这会导致密码根本不会出现在我的模型实例中吗?
例如,我有以下用户模型:
<?php
namespace App;
use Illuminate\Auth\Authenticatable;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Database\Eloquent\Model;
use Laravel\Lumen\Auth\Authorizable;
class User extends Model implements AuthenticatableContract, AuthorizableContract
{
use Authenticatable, Authorizable;
//protected $table = 'user';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['name', 'email', 'role'];
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
protected $hidden = ['password'];
public $timestamps = false;
}
Run Code Online (Sandbox Code Playgroud)
我现在正在运行一个控制器,它将新用户的姓名、电子邮件、密码和角色插入用户表中。在这里您可以看到该表: https: //i.stack.imgur.com/T3I2n.jpg
现在,当访问我的模型以插入新行时,如下所示: User::create($requestData);
出了问题...密码未插入。我调试了输入,数据就在那里,插入发生之前输入的 JSON 字符串如下所示:
{"name":"tester1","email":"test.tester1@tested.de","password":"3627909a29c31381a071ec27f7c9ca97726182aed29a7ddd2e54353322cfb30abb9e3a6df2ac2c20fe23436311d678564d0c8d305930575f60e2d3d048184d79","role":"Benutzer"}
Run Code Online (Sandbox Code Playgroud)
使用 php 函数对密码进行哈希处理hash("sha512", $password);。它基于“12345”,仅用于测试:D :P 正如预期的那样,散列密码具有所需的 128 个字符长度。
知道这种行为是否是由模型中定义为隐藏的密码属性引起的吗?
编辑:这就是我散列密码的方式:
$requestData["password"] = hash("sha512", $requestData["password"]);
Run Code Online (Sandbox Code Playgroud)
password密码不会被插入,因为您的数组中没有密码$fillable。
该$fillable数组是为了防止大量分配。如果您要从数组“填充”模型属性,则需要将属性名称添加到该数组中。
话虽如此,我实际上建议您不要添加password到$fillable数组中,而是在模型上显式设置密码:
$user = new User($requestData);
$user->password = $requestData["password"];
$user->save();
Run Code Online (Sandbox Code Playgroud)
正如评论中提到的,该$hidden属性纯粹用于模型转换为数组或转换为 JSON 时,因此它不应该对插入(或其他任何内容)产生影响。
| 归档时间: |
|
| 查看次数: |
7832 次 |
| 最近记录: |