Chaining methods with specific condition #33352
Unanswered
rac-augusto
asked this question in
General
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Hi guys, I was wondering about one thing.
Let's say we have the following case:
I guess it's a pretty common case, where we're having chained methods for an Eloquent model, and suddenly we have to stop the chain to satisfy a specific condition. Then, we return to the normal processing. Of course, it makes more sense with real world examples, but it's just to make a point.
I don't know if there is a way in Laravel to chain an
if
statement with Eloquent functions, for the sake of legibility. Sure, we're talking about conditions that refer to the same model, because we are talking about chaining, which imply returning$this
. I solved this "problem" (which could be categorised much better as a feature proposal) by doing this:So, the idea is pretty simple. I've created an
if
function that receives the condition and one required closure. If the condition is satisfied, then the closure is executed. We may pass a third parameter (an else callback), but it is not required. In this case, the function just returns$this
.But, again, I'm not sure whether Laravel has something like this or not.
What do you guys think?
Beta Was this translation helpful? Give feedback.
All reactions