在使用 Laravel 5.1 时,我尝试在使用 Eloquent ORM 将每个值保存到数据库之前检查每个值。我的逻辑是,如果该值为空字符串,则首先修剪该值""
,然后将其转换为null
而不仅仅是一个空字符串。
建议我创建一个 Trait 来重写 setAttribute 方法。
这就是我所做的
我在名为的文件内有一个新文件夹“app\Traits”TrimScalarValues.php
其中包含以下代码
<?php
namespace App\Traits;
trait TrimScalarValues
{
public function setAttribute($key, $value)
{
if (is_scalar($value)) {
$value = $this->emptyStringToNull(trim($value));
}
return $this->setAttribute($key, $value);
}
/**
* return null value if the string is empty otherwise it returns what every the value is
*
*/
private function emptyStringToNull($string)
{
//trim every value
$string = trim($string);
if ($string === ''){
return null;
}
return $string;
}
}
最后我有一个app\Models\Account.php
文件包含以下代码
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use App\Models\industry;
use App\Traits\RecordSignature;
use App\Traits\TrimScalarValues;
class Account extends Model
{
use RecordSignature, TrimScalarValues;
/**
* The database table used by the model.
*
* @var string
*/
protected $table = 'accounts';
protected $primaryKey = 'account_id';
const CREATED_AT = 'created_on';
const UPDATED_AT = 'modified_on';
const REMOVED_AT = 'purged_on';
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['client_id','account_name', 'company_code', 'legal_name', 'created_by','modified_by','instrucations'];
/**
* The attributes excluded from the model's JSON form.
*
* @var array
*/
//protected $hidden = ['account_id', 'remember_token'];
protected $guarded = ['account_id'];
/**
* Get the industry record associated with the account.
*/
public function industry()
{
return $this->hasOne(industry, industry::primaryKey);
}
public function pk(){
return $this->primaryKey;
}
}
但每次更新值时,我都会得到一个没有错误或日志的白页。
当我修改app\Models\Account.php
并改变use RecordSignature, TrimScalarValues;
to use RecordSignature;
然后我没有得到白页,但显然这些值没有被修剪并转换为空。
我在这里做错了什么?