Framework: Model Factory attributes returning primary key instead of Model

Created on 4 Sep 2017  路  5Comments  路  Source: laravel/framework

  • Laravel Version: 5.5.1
  • PHP Version: 7.0.22
  • Database Driver & Version:

Description:

In tests, when you make a model (not persisting it to the database) and specify an attributes array with a model, it expands the model and returns the primary key in place of the model.

Steps To Reproduce:

  • Create a test
  • Create models using
factory(Model::class)->make([
    'test' => factory(Test::class)->make()
]);
  • The test variable will contain the primary key of the Test class rather than the model

It looks like this was caused by #18499

All 5 comments

I'm not really sure what the point in make is now as opposed to create when make doesn't return the actual object. All articles about model factories suggest they are for testing. I get returning the id when you actually create the record in the DB as you have a reference to it, but what use is an id that refers to nothing. Could just hardcode an int instead.

factory(Model::class)->make([
    'test' => factory(Test::class)->make()
]);

This doesn't make sense to me, why would you want to assign a model instance to an attribute on another model?

So you could mimic passing around a model in your tests that has a relationship to another model. It's pretty much what is taught in Laracasts videos on testing using model factories. The recent changes in the framework seem to stop this being possible and I don't see why the change was made or what benefit it brings.

Agree with @Steven-Robinson, if your testing relationships, the initial change prevents this being done in this way. I get the need to have the primary key to get the model back out of the database but since we're not persisting anything it doesn't make sense.

This change was made since 5.4, it can't be changed now since it would be a breaking change, I suggest that you open a proposal in https://github.com/laravel/internals or suggest a change via a PR.

Closing since it's not a bug in the framework.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

kerbylav picture kerbylav  路  3Comments

PhiloNL picture PhiloNL  路  3Comments

klimentLambevski picture klimentLambevski  路  3Comments

YannPl picture YannPl  路  3Comments

Fuzzyma picture Fuzzyma  路  3Comments