Closed outhebox closed 5 years ago
You have to create two different filters. Then import both into your Resource like this:
public function filters(Request $request)
{
return [
new DateFrom,
new DateTo
];
}
@disitec Thanks for the fast reply, but i need to know how can i use where between with apply method in the two different filters as you mentioned, idk how exactly preform the query this?
Treat each filter as independent. Then in the apply method of each one, add a new constraint
// DateFrom
public function apply(Request $request, $query, $value)
{
return $query->where('date', '>=', $value);
}
// DateTo
public function apply(Request $request, $query, $value)
{
return $query->where('date', '<=', $value);
}
Thank you (Y)
Here how I did, based on comments above:
<?php
namespace App\Nova\Filters;
use Illuminate\Http\Request;
use R64\Filters\DateFilter;
abstract class Date extends DateFilter
{
/**
* Is the Date Filter is use for Date From.
*
* @var bool
*/
public $is_date_from = false;
/**
* Is the Date Filter is use for Date To.
*
* @var bool
*/
public $is_date_to = false;
/**
* Determine if the Date filter use for Date From.
*
* @return boolean
*/
public function isDateFrom()
{
return $this->is_date_from;
}
/**
* Determine if the Date filter use for Date To.
*
* @return boolean
*/
public function isDateTo()
{
return $this->is_date_to;
}
/**
* Get Date Operand.
*
* @return string
*/
public function getOperand()
{
if ($this->isDateFrom()) {
return '>=';
}
if ($this->isDateTo()) {
return '<=';
}
return '=';
}
/**
* Get Date Field From $date_field property.
*
* @return string
*/
public function getDateField()
{
return $this->date_field;
}
/**
* Apply the filter to the given query.
*
* @param \Illuminate\Http\Request $request
* @param \Illuminate\Database\Eloquent\Builder $query
* @param mixed $value
*
* @return \Illuminate\Database\Eloquent\Builder
*/
public function apply(Request $request, $query, $value)
{
return $query->where(
$this->getDateField(),
$this->getOperand(),
$value
);
}
/**
* Get the filter's available options.
*
* @param \Illuminate\Http\Request $request
*
* @return array
*/
public function options(Request $request)
{
return [
'dateFormat' => 'Y-m-d',
];
}
}
namespace App\Nova\Filters;
class DateFrom extends Date
{
public $date_field = 'created_at';
public $is_date_from = true;
}
namespace App\Nova\Filters;
class DateTo extends Date
{
public $date_field = 'created_at';
public $is_date_to = true;
}
...
public function filters(Request $request)
{
return [
new Filters\DateFrom(),
new Filters\DateTo(),
];
}
...
I have submitted PR as well - #10
Any documentation to how make a range filter [from - to] like the main demo?