Jay
Jay

Reputation: 43

Laravel Create Method does not return primary key values that were inserted by Observer

Let me preface this post with, I cannot change the method of inserting the primary key. This is being developed on a legacy system and I have no control over the method of retrieving the primary key, I just have to deal with it.

I have found that Laravel will not update the collection primary key when using the create method, with an observer that inserts the primary key value.

Here is my scenario (I have shrunk the models and files for space):

migration file:

Schema::create('forms_maps', function (Blueprint $table) {
    $table->integer('id')->unsigned();
    $table->string('name');
});

ModelObserver.php:

public function creating(Model $model)
{
    $countername = strtolower(class_basename(get_class($model))).'s_id';
    $model->id = tap(\App\Models\OCounter::where('countername',$countername)->first())->increment('counterval')->fresh()->counterval;
    Log::debug("Creating ". strtolower(class_basename(get_class($model))) . ": " . $model);
}

DatabaseSeeder.php:

$accountApp = \App\Models\FormsMap::create(['name' => 'Account Application']);
Log::debug("Created formsmap: " . $accountApp);

The output log:

Creating formsmap: {"name":"Account Application","id":84}
Created formsmap: {"name":"Account Application","id":0}

As you can see from the log, when the record is created using the create method, inside of the observer, I am getting the proper id; however, that value is not being passed back to the collection in the DatabaseSeeder. Am I looking at this incorrectly? Should I be using something else to insert the values into the tables? I do not want to insert this value manually/inline because every model has to have this information injected.

Thanks!

Upvotes: 1

Views: 1129

Answers (1)

Jay
Jay

Reputation: 43

GRRR!!!! I do this every time! The answer is:

The model needs to have the incrementing turned off.

class FormsMap extends Model
{
    public $timestamps = false;
    public $incrementing = false;

    ...
}

Heh!

Upvotes: 3

Related Questions