Refine for Laravel
A package by Hammerstone

Creating a Filter

Refine is a paid package. To purchase, head to hammerstone.dev.

Creating your first filter is as simple as creating a new class that extends Hammerstone\Refine\Filter. When you do that, you'll notice that there are two abstract methods that need to be implemented: initialQuery and conditions.

Typically you can put these in a top-level folder called Filters.

app/
├─ Console/
├─ Exceptions/
├─ Filters/
│ └─ EmployeeFilter.php
├─ Http/
├─ Models/
└─ Providers/
bootstrap/
config/
database/
public/
resources/
routes/
storage/

This is what your class would look like before we implement those methods:

use Hammerstone\Refine\Filter;
 
class EmployeeFilter extends Filter
{
public function initialQuery()
{
// @TODO
}
 
public function conditions()
{
// @TODO
}
}
Code highlighting powered by torchlight.dev, a Hammerstone product.

Initial Query

The initialQuery method is the starting point for every filter. This allows you, as the developer, to add restrictions into the base query that cannot be changed by the end user. In many cases you can simply use an empty model query:

public function initialQuery()
{
return Employee::query();
}

This works well in many cases, but not all of them. For instance, if you want to scope the entire filter by company_id, you can do so in the initialQuery:

public function initialQuery()
{
return Employee::where('company_id', Company::current()->id);
}

Or maybe you want to add in a scope:

public function initialQuery()
{
return Employee::active();
}

You're welcome to do anything you want in this method, as long as you return an Eloquent\Builder or Database\Builder class.

Conditions

Conditions are where you define what your users can filter on. If you wanted to let your users filter based on the employee's name, you could add a "name" condition.

public function conditions()
{
return [
TextCondition::make('name', 'Name')
];
}

The package comes with many conditions out of the box that you can use to build your perfect filter. To learn more about conditions, jump to the conditions overview page.