Laravel,带有隐藏属性的 Behat 和 Faker 问题

Laravel, Behat & Faker Issue with Hidden Attributes

我将 Laravel 与以下库一起使用:

在用户模型上我隐藏了密码属性,所以当我执行 GET 它按预期工作时,显示所有属性最少的密码

现在,当我使用从 Faker 创建的模型执行 POST 时,我无法发送属性密码。

Faker工厂

<?php

$factory->define(App\User::class, function (Faker\Generator $faker) {
    $role = App\Role::all()->random(1);
    return [ 
        'role_id' => $role->id,
        'username' => $faker->userName,
        'first_name' => $faker->firstName,
        'last_name' => $faker->lastName,
        'email' => $faker->safeEmail,
        'password' => str_random(10),
    ];
});

用户模型

<?php

namespace App;

use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{

protected $hidden = [ 'password' ];

/* rest of the code */
/* I have a validation rule for password to be required */

用户上下文函数

<?php
/**
 * @When I try to save a valid user   
*/
public function iTryToSaveAValidUser()
{
    $modelFake = factory('App\User')->make();
    $client = new GuzzleHttp\Client();
    $data['data'] = $modelFake;
    $res = $client->request('POST', url($this->apiURL . '/user'),[ 'json' => $data ]);
}

我收到的错误是需要密码,有没有办法只在 GET 时设置隐藏?

我"Fixed"这个问题与下面的代码有关,但我不喜欢这种方式

<?php
/**
 * @When I try to save a valid user   
*/
public function iTryToSaveAValidUser()
{
    $modelFake = factory('App\User')->make();
    $client = new GuzzleHttp\Client();
    $modelArray = $modelFake->toArray();
    $modelArray['password'] = str_random(10);
    $data['data'] = $modelArray;
    $res = $client->request('POST', url($this->apiURL . '/user'),[ 'json' => $data ]);
}

提前致谢!

我认为这是由于这条线

$res = $client->request('POST', url($this->apiURL . '/user'),[ 'json' => $data ]);

将属性发送为 json。

正确阅读这篇文章,它会有所帮助。

Hiding Attributes From JSON

有时您可能希望限制模型数组或 JSON 表示中包含的属性,例如密码。为此,请将 $hidden 属性 定义添加到您的模型中:

Note: When hiding relationships, use the relationship's method name, not its dynamic property name.

或者,您可以使用可见的 属性 定义应包含在模型数组和 JSON 表示中的属性白名单:

protected $visible = ['password']

临时修改属性可见性

如果您想让一些通常隐藏的属性在给定的模型实例上可见,您可以使用 makeVisible 方法。 makeVisible 方法 returns 方便方法链接的模型实例:

return $user->makeVisible('attribute')->toArray();