samedi 27 février 2016

Why are Laravel eloquent model attributes based on default definitions empty after save?

With a very simple model:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Example extends Model
{

}

And it's schema for completeness:

<?php

use App\Models\Lease;
use App\Models\Choice;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateTableExamples extends Migration {

    public function up()
    {
        Schema::create('example', function(Blueprint $table)
        {
            $table->increments('id');
            $table->enum('status', [1, 2, 3])->default(1);
            $table->text('abc')->nullable();
            $table->text('foo')->nullable();
        });
    }

    public function down()
    {
        Schema::dropIfExists('example');
    }
}

Why does the following save statement, result in empty attributes for the fields that are defined with defaults?

$example1 = new App\Models\Example();
$example1->foo = "BAR";
$example1->save();

var_dump($example1->attributes);

This outputs the following, note that the output has skipped the status field. Also note that field abc is missing.

array (size=4)
    'foo' => string 'BAR' (length=3)
    'id' => int 19

If I reload the model, with $example1->fresh(), I get the expected output:

array (size=4)
    'foo' => string 'BAR' (length=3)
    'abc' => null,
    'status' => int 1,
    'id' => int 19

Is there a way to avoid the fresh method? Under the hood, fresh is another trip to the db.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire