1
votes

I am implementing a date filter on my orders table e.g. return all orders that where 'created_at' today, last week, last month, on a specific date or between two dates.

I know that laravel has dedicated where methods such as "whereDay", "whereMonth" and others.

So far I have written a big switch statement for each condition like his:

switch($date_filter){
   case 'today':
     $orders = Order::whereDay('created_at','=',date('d')->get();
   break;
   // case for each date filter type 
}

My question is whether there is generate the date filter part of the query separately, so I could do something like this:

$orders = Order::whereRaw($this->getDateFilterAsSql($date_filter)->get();

so that I would not have to repeat the entire query for each date_filter type?

1

1 Answers

0
votes

You can create multiple local scopes and use them:

$this->order->$date_filter()->get();

An example of a local scope:

public function scopeToday($query)
{
    return $query->whereDay('created_at', date('d'));
}

You also can use a model as a repository and do this:

$this->order->$date_filter();

An example of a method in Order model:

public function today()
{
    return $this->whereDay('created_at', date('d'))->get();
}