Filters

Filters in the portal help narrow down a query by passing an array to them.

Please extend the App\Filters\Filter class instead of using it directly, although using it directly would work.

Instantiating a filter

To instantiate you simply create a new instance of the filter class, in this case the ApplicantFilter.

The class expects two parameters. The first is an array of key value pairs (the filters), and the second a Illuminate\Database\Eloquent\Builder instance.

$filter = new ApplicantFilter([
    'country_of_residence' => ['Norway', 'Sweden']
], Applicant::query());

To get a filtered query builder you can call the build method.

$query = $filter->build();

Or do it all in one go:

$query = (new ApplicantFilter([
    'country_of_residence' => ['Norway', 'Sweden']
], Applicant::query()))->build();

Working with filters

Using the example above we can build the actual query inside the ApplicantFilter.

All keys are converted to studly case and prepended with the filter keyword, so in this case we'd end up with filterCountryOfResidence. The Filter class will look for that as a method on the object. The method would accept one argument; $value.

protected function filterCountryOfResidence($value)
{
    //
}

To access the builder you simply use the $this->builder property and pass the request to the appropriate scope or build the query directly.

protected function filterCountryOfResidence($value)
{
    $this->builder->whereHas('country_of_residence', function($query) use ($value) {
        $query->whereIn('name', array_wrap($value));
    });
}