An ->only()
method in query builder.
#43677
Unanswered
BrekiTomasson
asked this question in
Ideas
Replies: 2 comments 1 reply
-
I would think that
|
Beta Was this translation helpful? Give feedback.
1 reply
-
I just discovered that Laravel already has something very much like this implemented already, in the |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
What I'm suggesting here is for an
->only()
method (or something with a better name, obviously) which returns the result of the query, but only if there is a single result. If the query, as stated at that point, has more than one result, it would throw an Exception. Think of it as a->firstOrFail()
but with the added check of requiring there to be only a single result.Currently (to the best of my knowledge, at least), the only way to do this is in multiple steps, first you
->get()
the results, then you->count()
the results, and if the count is not exactly one (so if it is zero or 2+), you throw an exception manually, otherwise you continue as intended.This would be used in scenarios where
->firstOrFail()
still runs the risk of grabbing the wrong item if the query is not clear enough or if there are too many moving parts involved to be sure that you've narrowed down the search properly. It would also more clearly show where you have potential issues in your database, such as when you have a column that should be->unique()
in your migration but isn't.Examples of use:
Beta Was this translation helpful? Give feedback.
All reactions