Reputation: 3234
Is it possible to "append" queries in Laravel
?
For example like so in this example code:
function crunchNumbersForToday()
{
return $this->crunchSomeInformationInRange(Payments::where('created_at', Carbon::now()));
}
function crunchNumbersInRange($range)
{
$paymentsToCrunch = Payment::where('state', 'payed')->append($range)->get();
// Work with the payments
}
So in this case the where
of the created_at
field would be appended to the query where state
equals payed
. Which would make something like: where created_at = '2015-07-08 12:00' AND state = payed
.
Upvotes: 3
Views: 11029
Reputation: 4833
I think you could create a scope
.
For your code that would be (in your Payment
model):
function scopeToday($query)
{
return $query->where('created_at', Carbon::now());
}
function scopeNumbersInRange($query)
{
return $query->where('state', 'payed');
// Work with the payments
}
And then call it elsewhere in your code like:
Payment::numbersInRange()->today()->get();
Edit: You can make them dynamic too:
function scopeDate($query, $date)
{
return $query->where('created_at', $date);
}
...
Payment::numersInRange()->date(Carbon::now())->get();
And so on. This way you can keep chaining scopes.
Upvotes: 7