Skip to content

Conversation

@MasterRO94
Copy link
Contributor

This PR allows using firstOrCreate and firstOrNew without parameters.
Useful for tables with default parameters or where all fields are nullable.

For example:

$user->profile()->firstOrNew();

$settings = Settings::firstOrCreate();

For now, we should explicitly pass an empty array and it looks like something is wrong.

@GrahamCampbell GrahamCampbell changed the title [8.x] allow to call firstOrNew and firstOrCreate without parameters [8.x] Allow to call firstOrNew and firstOrCreate without parameters Jun 25, 2020
@GrahamCampbell GrahamCampbell changed the title [8.x] Allow to call firstOrNew and firstOrCreate without parameters [8.x] Support calling firstOrNew/Create without parameters Jun 25, 2020
@GrahamCampbell
Copy link
Collaborator

GrahamCampbell commented Jun 25, 2020

@gocanto Can you explain why the 👎, otherwise your feedback can't be used.

@gocanto
Copy link
Contributor

gocanto commented Jun 25, 2020

@GrahamCampbell yes, I can. 👯

These methods are really a low-level implementation in my opinion and they should be as strict as possible. This method as it stands right now brings a side effect of creating a new record if a given query did not return values. So, stacking yeat another functionality on top of it will hide the rabbit tail even more.

In spite of I share the idea of convenience, I personally believe this is more an app concern than frameworks. Nevertheless, If it were to stay, I will suggest a separate method more aligned with Laravel fashion. Like, createEmpty or CreateWithDefaults

@MasterRO94
Copy link
Contributor Author

@gocanto
Eloquent Builder::firstOrNew already have an empty array for $attributes. This PR adds the same behavior for firstOrCreate and HasOneOrMany overrides.

And for now the signature for Builder::firstOrNew and HasOneOrMany::firstOrNew is different.

@GrahamCampbell
Copy link
Collaborator

Maybe we should change the other method to be stricter too then?

@MasterRO94
Copy link
Contributor Author

@GrahamCampbell
I think it's up to a developer to either pass parameters or not, IMO.
For one-to-one relations, it will be a good case to just call firstOrNew/firstOrCreate without params.
For now, I just pass an empty array.

@taylorotwell taylorotwell merged commit f8fd88f into laravel:master Jun 25, 2020
@taylorotwell
Copy link
Member

I've definitely had situations where I needed to pass an empty array so I think this is generally OK.

@GrahamCampbell
Copy link
Collaborator

I've definitely had situations where I needed to pass an empty array

The discussion was if that should be explicitly done by developer or not.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants