mercredi 2 août 2017

Laravel / Eloquent model attributes - prevent null values from saving as empty string?

I'm using an Eloquent model in a new system for a site, and I'm trying to seed some data from our old, messy, mySQL database to our new eloquent system in front of a postgres DB. In order to keep the new data cleaner, I'm enforcing strict constraints on the new data.

Here's some code.

In the migration for the model:

$table->string('email', 50)->unique()->nullable();

In the model itself:

<?php

namespace App;

use App\Traits\EmptyIsNull;
use Illuminate\Database\Eloquent\Model;

class Example extends Model
{
    use EmptyIsNull;
    protected $fillable = ...
    public function setEmailAttribute($value)
    {
        $this->attributes['email'] = strtolower($value);
    }
    ...
}

App\Traits\EmptyIsNull:

<?php

namespace App\Traits;

trait EmptyIsNull
{
    public function setAttribute($key, $value)
    {
        if (empty($value)) {
            $value = null;
        }

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

However, when I run php artisan migrate:refresh --seed, the email is set to an empty string when it's empty in the old database, thereby becoming an issue with the second empty email:

SQLSTATE[23505]: Unique violation: 7 ERROR:  duplicate key value violates unique constraint "examples_email_unique"

What am I doing wrong? The EmptyIsNull is certainly being called, as an echo statement put there is often output. Is laravel/eloquent converting back from null to empty string? or is postgres doing it?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire