如何使用Laravel 5.1将空字符串更改为null?

时间:2015-07-29 18:46:18

标签: php laravel traits laravel-5.1

在使用Laravel 5.1时,我试图在使用Eloquent ORM将数据保存到数据库之前检查每个值。我的逻辑是,首先修剪该值,如果该值为空字符串"",则将其转换为null而不是仅仅为空字符串。

我被建议创建一个Trait,它会覆盖setAttribute方法。

所以这就是我所做的

我在名为TrimScalarValues.php的文件中有一个新文件夹“app \ Traits”,其中包含以下代码

<?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;更改为use RecordSignature;时,我没有获得白页,但显然这些值未被修剪并转换为空。

我在这里做错了什么?

4 个答案:

答案 0 :(得分:5)

您无法在特质中调用$this->setAttribute()。相反,您希望使用setAttribute

调用“原始”parent::方法
public function setAttribute($key, $value)
{
    if (is_scalar($value)) {
        $value = $this->emptyStringToNull(trim($value));
    }

    return parent::setAttribute($key, $value);
}

关于空日志,您是否已检查过框架中的Web服务器日志?

答案 1 :(得分:5)

我遇到了同样的问题,并通过创建一个过滤空输入字段的中间件来解决它。

Public dictOfNewThinkFuncsToAdd As New Dictionary (Of ?, Single) 'Function/Sub, Time To Call

Private Sub Main()
    Dim dictOfThinkFuncs As New Dictionary (Of ?, Single) 'Function/Sub, Time To Call
    dictOfThinkFuncs.Add(AddressOf(Sub1), GetCurrentTime() + 5)
    dictOfThinkFuncs.Add(AddressOf(Sub2), GetCurrentTime() + 6)
    Dim removalQueue As New List(Of ?)

    Do
        Dim bRemoveFunc As Boolean = False
        Dim bAddFunc As Boolean = False
        For iter As Integer = 0 To dictOfThinkFuncs.Count - 1
            If GetCurrentTime() >= dictOfThinkFuncs(iter).Value Then
                CallFunction(dictOfThinkFuncs(iter).Key)
                removalQueue.Add(dictOfThinkFuncs(iter).Key)
                bRemoveFunc = True
            End If
        Next

        If bRemoveFunc Then
            For Each func In removalQueue
                dictOfThinkFuncs.Remove(func)
            Next
            removalQueue.Clear()
        End If

        For Each func In dictOfNewThinkFuncsToAdd
            dictOfThinkFuncs.Add(func.Key, func.Value)
            bAddFunc = True
        Next

        If bAddFunc Then
            dictOfNewThinkFuncsToAdd.Clear()
        End If

    Threading.Thread.Sleep(10)
    Loop
End Sub

Private Sub Sub1()
    DoStuff()
    dictOfNewThinkFuncsToAdd.Add(AddressOf(Sub3), GetCurrentTime() + 15)
End Sub

Private Sub Sub2()
    DoStuff()
    dictOfNewThinkFuncsToAdd.Add(AddressOf(Sub2), GetCurrentTime() + 15)
End Sub

Private Sub Sub3()
    DoStuff()
End Sub

不要忘记将自定义中间件添加到Http / Kernel.php

Laracasts

找到了这个

答案 2 :(得分:1)

你可能想看看这个包: https://packagist.org/packages/iatstuti/laravel-nullable-fields

&#34;这会创建一个特征,并允许您轻松标记在持久保存到数据库时应设置为null的属性。&#34;

我知道这篇文章很老了,当时这个软件包可能还没有存在。

答案 3 :(得分:-1)

您可以在模型中使用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;
    }
}

每当您使用Eloquent更新或插入记录时,account_name将通过此mutator传递。