首页 > 解决方案 > $hidden 在 eloquent 模型中究竟有什么作用?

问题描述

我目前正在摆弄 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:

我不明白这有什么影响。如果我有一个插入密码的查询,我应该隐藏它吗?或者这会导致密码根本不出现在我的模型实例中吗?

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

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

现在,当访问我的模型以插入这样的新行时: User::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"]);

标签: laraveleloquentlumen

解决方案


password由于您的$fillable阵列中没有密码,因此不会插入密码。

$fillable数组是为了防止批量分配。如果要从数组中“填充”模型属性,则需要将属性名称添加到该数组中。

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

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

正如评论中提到的,该$hidden属性纯粹用于将模型转换为数组或转换为 JSON 时,因此它不应该对插入(或其他任何东西)产生影响。


推荐阅读