Laravel Eloquent: add queries

Can I "add" queries to Laravel

?

For example, for example, in this example the 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

fields created_at

will be added to the query, where state

is payed

. What would you do something like this: where created_at = '2015-07-08 12:00' AND state = payed

.

+3


source to share


1 answer


I think you could create scope

.

For your code that would be (in your model Payment

):

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, for example:

Payment::numbersInRange()->today()->get();

      



Edit: You can also make them dynamic:

function scopeDate($query, $date)
{
    return $query->where('created_at', $date);
}

      

...

Payment::numersInRange()->date(Carbon::now())->get();

      

Etc. This way you can keep the chain regions.

+2


source







All Articles