流明PHP:模型中的隐藏密码字段未使用Model-> fill()填充

时间:2017-11-19 19:28:23

标签: php laravel http passwords lumen

我的API用户注册代码一直存在问题。

我有一个UserController,它接收发布的数据并验证字段。然后它会将数据发送到我的UserService类中的SignUpUser方法,该类创建用户模型并填写所有给定数据并将其发送到将其发送到我的数据库的UserRepository。

当我dd()我的$password已填满时,但当我dd()填写$user时,该字段返回null ...我不知道为什么它没有填充它还没有。

我的代码截图:

UserController中

public function signUpUser(Request $request)
{
    $this->validate($request,[
        'username' => 'required|regex:/^[(a-zA-Z\s)(0-9\s)]+$/u|min:3',
        'email' => 'required|email',
        'password' => 'required|min:8',
        'displayname' => 'required|regex:/^[(a-zA-Z\s)(0-9\s)]+$/u|min:3',
    ], [
        'min' => 'The :attribute must at least be :min characters long.',
    ]);

    $user = $this->userService->signUpUser(
        $request->get('username'),
        $request->get('email'),
        $request->get('password'),
        $request->get('displayname')
    );



    if($user)
    {
        //alright! user has been made
        $response = ['status' => 'OK', 'message' => "User {$user->username} has successfully been created"];
    }
    else
    {
        //something went wrong
        $response = ['status' => 'FAIL', 'message' => "Something went wrong or user already exists in DB"];
    }

    return response()->json($response, 201);
}

UserService

public function signUpUser($userName, $email, $password, $displayName)
{
    $password = password_hash($password, PASSWORD_DEFAULT);

    $user = $this->userRepository->signUpNewUser($userName, strtolower($email), $password, $displayName);
    $user = $this->userRepository->get($user->pk);
    //TODO: send user signup mail soon
    return $user;
}

UserRepository

public function signUpNewUser($username, $email, $password, $displayName)
{
    $user = $this->getModel();
    $user->fill(
        [
            'username' => $username,
            'email' => $email,
            'password' => $password,
            'displayname' => $displayName,
        ]);
    dd($user::all());
    $user->save();
    return $user;
}

的usermodel

class UserModel extends BaseModel
{

/**
 * The database table used by the model.
 *
 * @var string
 */
protected $table = 'users';


/**
 * The attributes that are mass assignable.
 *
 * @var array
 */
protected $fillable = [
'username', 'email', 'displayname'
];

/**
 * The attributes excluded from the model's JSON form.
 *
 * @var array
 */
protected $hidden = [
    'password',
];
}

填写数据后转储$ user Dumped $user after filling in data

1 个答案:

答案 0 :(得分:1)

将其添加到$fillable

protected $fillable = ['username', 'email', 'displayname', 'password'];

此外,请勿在数据库中保留未加密的密码,请使用bcrypt()

'password' => bcrypt($password),