gpt4 book ai didi

php - 没有可填充属性的 laravel Eloquent 创建

转载 作者:行者123 更新时间:2023-11-30 21:56:48 27 4
gpt4 key购买 nike

这是我的模型:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use App\Models\BaseModel;
use Illuminate\Support\Facades\Hash;

class Domain extends BaseModel {

protected $fillable = ['user_id', 'name', 'username', 'password', 'plan', 'payment', 'status', 'duration'];
protected $hidden = ['password'];

protected $rules = [
'user_id' => [
'required',
'integer',
'exists:users,id'
],
'name' => [
'required',
'regex:/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+(?:[a-z][a-z0-9-]{0,61}[a-z0-9])$/i',
'unique:domains,name',
],
'username' => [
'sometimes',
'nullable',
'min:1',
'max:16',
'unique:domains,username',
],
'password' => [
'sometimes',
'nullable',
'min:0',
'max:65',
],
'plan' => [
'sometimes',
'nullable',
],
'payment' => [
'required',
'string',
'max:40',
'in:webpos,cheque'
],
'status' => [
'sometimes',
'nullable',
'integer',
'in:0,1',
],
'duration' => [
'sometimes',
'nullable',
'integer',
'min:1',
'max:10',
]
];

protected $attributeNames = [
'user_id' => 'Domain Sahibi',
'name' => 'Domain Adı',
'payment' => 'Ödeme Şekli',
'status' => 'Domain Durumu',
'duration' => 'Domain Süresi'
];

public function setUsernameAttribute($value)
{
if ( is_null($value) ){
$value = str_random(16);
}
$this->attributes['username'] = strtolower($value);
}

public function setPasswordAttribute($value)
{
if ( is_null($value) ){
$value = str_random(16);
}
$this->attributes['password'] = Hash::make($value);
}

public function setPlanAttribute($value)
{
$this->attributes['plan'] = strtolower($value);
}

public function setNameAttribute($value){
$this->attributes['name'] = str_replace('www.', '', $value);
}

public function setStatusAttribute($value)
{
if ( is_null($value) ){
$value = 0;
}

$this->attributes['status'] = (int)$value;
}

public function setDurationAttribute($value)
{
if ( is_null($value) ){
$value = 1;
}

$this->attributes['duration'] = $value;
}
}

这是我的 Controller :

$req = $request->only(['user_id', 'name', 'payment', 'status', 'duration']);
$result = $this->domain->add($req);

我得到了这个错误

"Invalid Request SQLSTATE[HY000]: General error: 1364 Field 'username' doesn't have a default value (SQL: insert into domains (user_id, name, payment, status, duration, updated_at, created_at) values (1, deneme-1.com, cheque, 0, 1, 2017-07-03 13:58:03, 2017-07-03 13:58:03))"

为什么用户名和密码去sql?

我将这些添加到可填充数组中。我不明白为什么它不起作用?

我不希望用户名和密码随请求一起出现。我想设置默认的 str_random。但不工作?

问题出在哪里?

这是为 null come 属性设置默认属性的正确方法吗?

最佳答案

因为你把 'username' 放在了变量 $fillable var并且您数据库中的必须是 可空() .

关于php - 没有可填充属性的 laravel Eloquent 创建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44884032/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com