$ hidden在雄辩的模式中究竟具有什么作用?

时间:2019-12-19 10:54:00

标签: laravel eloquent lumen

我目前正在以雄辩的方式与Lumen和Im进行数据库交互。 我已经阅读了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:

我不知道这意味着什么。如果我在要插入密码的查询中将其隐藏?还是这会导致密码根本不出现在我的模型实例中?

例如,我具有以下用户模型:

<?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;
}

我现在正在运行一个控制器,该控制器应在用户表中插入新用户的名称,电子邮件,密码和角色。 在这里您可以看到表格: https://imgur.com/8r2JjPh

现在,在访问模型以插入新行时,如下所示: 用户:: create($ requestData);

出了点问题... 密码未插入。 我调试了输入,数据在那里,在插入之前输入的JSON字符串看起来像这样:

{"name":"tester1","email":"test.tester1@tested.de","password":"3627909a29c31381a071ec27f7c9ca97726182aed29a7ddd2e54353322cfb30abb9e3a6df2ac2c20fe23436311d678564d0c8d305930575f60e2d3d048184d79","role":"Benutzer"}

使用php函数hash("sha512", $password);对密码进行了哈希处理。其基于“ 12345”,仅用于测试:D:P 哈希密码符合预期的128个字符的长度。

您知道这种行为是否是由于将密码属性定义为隐藏在模型中引起的吗?

编辑: 这是我对密码进行哈希处理的方式:

$requestData["password"] = hash("sha512", $requestData["password"]);

2 个答案:

答案 0 :(得分:1)

由于password数组中没有$fillable,因此不会插入密码。

$fillable数组用于防止批量分配。如果要“填充”阵列中的模型属性,则需要将属性名称添加到该阵列中。

话虽如此,我实际上建议您不要将password添加到$fillable数组中,而是在模型上显式设置密码:

$user = new User($requestData);
$user->password = $requestData["password"];
$user->save();

如评论中所述,$hidden属性仅用于将模型强制转换为数组或转换为JSON时,因此它不会对插入(或其他任何内容)产生影响。

答案 1 :(得分:1)

protected $ hidden是一个数组,并且是Model类的参数,它的作用是在查询结果中隐藏数据库中的列(数组中)。在您的示例中,$ hidden = ['password']在用户结果中显示不可见的“ password”列。

https://laravel.com/api/5.7/Illuminate/Database/Eloquent/Model.html'受保护的数组$ hidden应该为序列化隐藏的属性。'