如何使用 Laravel 5.1 将空字符串更改为 null?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31708707/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to change empty string to a null using Laravel 5.1?
提问by Junior
While using Laravel 5.1, I am trying to check every value before it is saved in the database using Eloquent ORM. My logic is, first trim the value, if the value is an empty string ""
, then to convert it to null
instead of just an empty string.
在使用 Laravel 5.1 时,我试图在使用 Eloquent ORM 将每个值保存到数据库之前检查每个值。我的逻辑是,首先修剪该值,如果该值是一个空字符串""
,则将其转换为null
而不是一个空字符串。
I was advised to create a Trait which will override the setAttribute method for that.
我被建议创建一个 Trait 来覆盖 setAttribute 方法。
So here is what I have done
所以这就是我所做的
I have a new folder "app\Traits" inside of a file called TrimScalarValues.php
which contains the following code
我在一个名为的文件中有一个新文件夹“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;
}
}
Finally I have a app\Models\Account.php
file which contains the following code
最后我有一个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;
}
}
But every time I update a value, I get a white page with no error or logs.
但是每次我更新一个值时,我都会得到一个没有错误或日志的白页。
When I modify the app\Models\Account.php
and change use RecordSignature, TrimScalarValues;
to use RecordSignature;
then I do not get a white page but obviously the values are not trimmed and converted to null.
当我修改app\Models\Account.php
并更改use RecordSignature, TrimScalarValues;
为use RecordSignature;
then 我没有得到白页但显然这些值没有被修剪并转换为空值。
What am I doing wrong here?
我在这里做错了什么?
回答by lukasgeiter
You can't call $this->setAttribute()
in your trait. Instead you want to call the "original" setAttribute
method by using parent::
:
你不能呼唤$this->setAttribute()
你的特质。相反,您想setAttribute
使用parent::
以下方法调用“原始”方法:
public function setAttribute($key, $value)
{
if (is_scalar($value)) {
$value = $this->emptyStringToNull(trim($value));
}
return parent::setAttribute($key, $value);
}
Regarding the empty logs, have you checked the webserver log besides the one from the framework?
关于空日志,除了框架中的日志之外,您是否检查过网络服务器日志?
回答by Lukas
I had the same problem and solved it by creating a middleware that filters empty input fields.
我遇到了同样的问题,并通过创建一个过滤空输入字段的中间件来解决它。
public function handle($request, Closure $next) {
$input = $request->all();
if ($input) {
array_walk_recursive($input, function (&$item) {
$item = trim($item);
$item = ($item == "") ? null : $item;
});
$request->merge($input);
}
return $next($request);
}
Don't forget to add your custom middleware to Http/Kernel.php
不要忘记将您的自定义中间件添加到 Http/Kernel.php
Found this at Laracasts
在Laracasts 上找到了这个
回答by HamzStramGram
You might wanna take a look at this package: https://packagist.org/packages/iatstuti/laravel-nullable-fields
你可能想看看这个包:https: //packagist.org/packages/iatstuti/laravel-nullable-fields
"This create a trait and allows you to easily flag attributes that should be set as null when being persisted to the database."
“这会创建一个特征,并允许您轻松标记在持久保存到数据库时应设置为 null 的属性。”
I know this post is old, and at that time this package maybe didn't exist yet.
我知道这篇文章很旧,当时这个包可能还不存在。
回答by Vitaliy Gura
You can use mutator in you model. For the field account_name mutator should looks like this:
您可以在模型中使用 mutator。对于字段 account_name mutator 应该如下所示:
public function setAccountNameAttribute($account_name)
{
if(is_null($account_name))
{
$this->attributes['account_name'] = null;
}
else
{
$this->attributes['account_name'] = $account_name;
}
}
And everytime when you will update or insert the record using Eloquent, account_name will be passed through this mutator.
每次当你使用 Eloquent 更新或插入记录时, account_name 都会通过这个 mutator 传递。