Skip to content

Conversation

@sethsandaru
Copy link
Contributor

Hi team,

It is quite a normal use case that we use find or findOrFail multiple times within the same request - which results in multiple queries to the database.

The usual workaround is to cache the result via static properties or a Context, but that adds another unnecessary layer in userland.

So this PR introduces the findOnce and findOrFailOnce methods. Both are nice-to-have and provide a small performance improvement per request.

Personal taste: I did add these methods using macro, but I don't really like macro. Extending Builder is fine, but then I’d have to create a new BaseModel to use that extended Builder class, etc.

(If this gets accepted, I’ll open a PR to update the docs.)

*
* @param mixed $id
* @param array|string $columns
* @return ($id is (\Illuminate\Contracts\Support\Arrayable<array-key, mixed>|array<mixed>) ? \Illuminate\Database\Eloquent\Collection<int, TModel> : TModel|null)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't find() always return TModel? For \Illuminate\Database\Eloquent\Collection<int, TModel>, we have get()

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can pass an array/collection of IDs to fetch multiple records, though (it’s also mentioned in the original phpDoc of find and findOrFail)

But same here - I also always use find for fetching a single record and get() for a list 😄

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

But what was the decision to not have a getOnce()?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That could be a good follow-up candidate after this one - but first, we probably want to see whether the Laravel team is open to the whole *Once idea.

@taylorotwell
Copy link
Member

Thanks for your pull request to Laravel!

Unfortunately, I'm going to delay merging this code for now. To preserve our ability to adequately maintain the framework, we need to be very careful regarding the amount of code we include.

If applicable, please consider releasing your code as a package so that the community can still take advantage of your contributions!

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.

3 participants