So ändern Sie leere Zeichenfolge in einen null-mit Laravel 5.1?

Während der Verwendung von Laravel 5.1, versuche ich zu überprüfen, jeden Wert, bevor es gespeichert wird in der Datenbank mit Eloquent ORM. Meine Logik ist, zuerst trimmen Sie den Wert, wenn der Wert eine leere Zeichenfolge "", dann konvertieren null statt nur einen leeren string.

Mir wurde geraten, zu erstellen, eine Eigenschaft, die wird, überschreiben die setAttribute-Methode für, die.

So, hier ist was ich getan habe

Habe ich einen neuen Ordner "app\ "Traits" in einer Datei namens TrimScalarValues.php die den folgenden code enthält

<?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;
    }
}

Endlich habe ich ein app\Models\Account.php - Datei, die den folgenden code enthält

<?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;
    }

}

Aber jedes mal, wenn ich aktualisieren einen Wert, bekomme ich eine weiße Seite ohne Fehlermeldung oder logs.

Wenn ich änderungen an der app\Models\Account.php und ändern use RecordSignature, TrimScalarValues; zu use RecordSignature; dann habe ich nicht eine weiße Seite erhalten, aber offensichtlich sind die Werte nicht getrimmt und zu null umgewandelt.

Was mache ich hier falsch?

InformationsquelleAutor Junior | 2015-07-29
Schreibe einen Kommentar