Refine will be launching soon 🎉 Sign up for the early access list to stay up to date.
Refine for Laravel
A package by Hammerstone

Custom Conditions

Hammerstone Refine has not launched yet. Sign up for the early access list to stay up to date!

We have done our best to provide you with as many conditions as is possible, but there are going to be times where you may need a different kind of condition that we don't supply out of the box.

For our example, we're going to pretend that you need to filter by a distance from an address. Having this type of condition out of the box is beyond the scope of this package, but may be useful to your specific app.

Let's take a look at how we would build that out.

Creating the Class

The very first thing you need to do is create a new class that extends the base Condition class provided to you by the package. This will give you several helpful methods right off the bat.

Your editor will most likely show you one method that is declared abstract in the Condition class, left up to you to implement.

If you stub it out, you should now have the following:

1class DistanceFromAddressCondition extends Condition
2{
3 public function applyCondition($query, $input)
4 {
5 // TODO: Implement applyCondition() method.
6 }
7}

Attributes and Clauses

Most of the time, you will be applying your logic against an attribute on a model which is backed by a column in a database table. Because this is an extremely common use case, we have provided a UsesAttributes trait that brings along a few helpful methods.

Another common use case is to have "clauses" for your condition. Clauses are phrases like "is less than", "is greater than", "contains", "does not contain", etc. Most conditions have clauses. To that end, we also provide a HasClauses trait to make that simpler.

In our example here, we are not going to apply our logic against an attribute, but we are going to have clauses, so we'll add that trait and stub out the methods it requires.

1class DistanceFromAddressCondition extends Condition
2{
3 use HasClauses;
4 
5 protected function clauses()
6 {
7 // TODO: Implement clauses() method.
8 }
9 
10 public function applyCondition($query, $input)
11 {
12 // TODO: Implement applyCondition() method.
13 }
14}
Code highlighting powered by torchlight.dev, a Hammerstone product.

To keep the example simple, we'll let the user choose between "Is Near" and "Is Not Near" for their clauses.

1class DistanceFromAddressCondition extends Condition
2{
3 use HasClauses;
4 
5 const CLAUSE_NEAR = 'near';
6 const CLAUSE_NOT_NEAR = 'not';
7 
8 protected function clauses()
9 {
10 return [[
11 'id' => static::CLAUSE_NEAR,
12 'display' => 'Is Near'
13 ], [
14 'id' => static::CLAUSE_NOT_NEAR,
15 'display' => 'Is Not Near'
16 ]];
17 }
18 
19 public function applyCondition($query, $input)
20 {
21 // TODO: Implement applyCondition() method.
22 }
23}

Because we're measuring distance, we'll need to allow the developer to pass in the latitude and longitude columns. We'll add methods for that.

1class DistanceFromAddressCondition extends Condition
2{
3 use HasClauses;
4 
5 const CLAUSE_NEAR = 'near';
6 const CLAUSE_NOT_NEAR = 'not';
7 
8 public $latitude;
9 public $longitude;
10 
11 protected function clauses()
12 {
13 return [[
14 'id' => static::CLAUSE_NEAR,
15 'display' => 'Is Near'
16 ], [
17 'id' => static::CLAUSE_NOT_NEAR,
18 'display' => 'Is Not Near'
19 ]];
20 }
21 
22 public function latlon($lat, $lon)
23 {
24 $this->latitude = $lat;
25 $this->longitude = $lon;
26 
27 return $this;
28 }
29 
30 public function applyCondition($query, $input)
31 {
32 // TODO: Implement applyCondition() method.
33 }
34}

Ensurance

To ensure that you always configure everything correctly, you can and some "ensurance" in the boot method:

1class DistanceFromAddressCondition extends Condition
2{
3 public function boot()
4 {
5 $this->addEnsurance([$this, 'ensureLatLonConfigured']);
6 }
7 
8 // [Omitted methods]
9 
10 protected function ensureLatLonConfigured()
11 {
12 if (!$this->latitude || !$this->longitude) {
13 throw new ConfigurationException(
14 'Latitude and longitude attributes must both be configured.'
15 );
16 }
17 }
18}

Add ensurance to ensure the developer has set things up correctly.

Add validation to validate that the user has given you good data.

Several of the standard conditions ensure certain aspects are configured correctly. Adding ensurance provides reasonable errors to the developer early, instead of failing in mysterious ways later.

Validating

Adding ensurance ensures that the developer has configured the condition properly, but you'll also want to validate the user's input. You can add rules in the boot method as well.

We're going to add a validation rule to test that the user has entered a valid, geocode-able address:

1class DistanceFromAddressCondition extends Condition
2{
3 public function boot()
4 {
5 $this->addEnsurance([$this, 'ensureLatLonConfigured']);
6 
7 $this->addRules([
8 'value' => [
9 'required',
10 // Any custom Laravel rule (outside the scope of this example)
11 new AddressCanBeFoundRule
12 ]
13 ]);
14 }
15 
16 // [Omitted methods]
17}

Applying the User's Input

Now for the fun part: applying the user's input to the query.

Once you reach the applyCondition method you know that you're working with valid data based on the validation rules, and a valid configuration based on the ensurance.

Two parameters are passed to the applyCondition method, where we do all of our work. The query parameter is the Eloquent (or Base) query, against which you apply your wheres, whereNots, or anything else your condition may require.

The input variable will contain everything that the user has chosen. Because we're reusing the frontend from the Text Condition, we know that input will contain a clause and a value key.

1class DistanceFromAddressCondition extends Condition
2{
3 // [Omitted methods]
4 
5 public function applyCondition($query, $input)
6 {
7 // If the user has chose "near", then we're looking for
8 // records less than a certain distance away, so we'll
9 // use the `<` operand.
10 $operand = $input['clause'] === static::CLAUSE_NEAR ? '<' : '>';
11 
12 // Geocode the address (outside the scope of the example).
13 $address = Geocoding::code($input['value']);
14 
16 $sql = <<<SQL
17(
18 ST_Distance_Sphere(
19 point({$this->longitude}, {$this->latitude}),
20 point(?,?)
21) * .000621371192) $operand ?
22SQL;
23 
24 // Apply to the query.
25 $query->whereRaw($sql, [
26 $address->longitude,
27 $address->latitude,
28 $miles = 5
29 ]);
30 }
31}

This leaves us with the final class:

1class DistanceFromAddressCondition extends Condition
2{
3 use HasClauses;
4 
5 const CLAUSE_NEAR = 'near';
6 const CLAUSE_NOT_NEAR = 'not';
7 
8 public $latitude;
9 
10 public $longitude;
11 
12 public function boot()
13 {
14 $this->addEnsurance([$this, 'ensureLatLonConfigured']);
15 
16 $this->addRules([
17 'value' => [
18 'required',
19 new AddressCanBeFoundRule
20 ]
21 ]);
22 }
23 
24 protected function clauses()
25 {
26 return [[
27 'id' => static::CLAUSE_NEAR,
28 'display' => 'Is Near'
29 ], [
30 'id' => static::CLAUSE_NOT_NEAR,
31 'display' => 'Is Not Near'
32 ]];
33 }
34 
35 public function latlon($lat, $lon)
36 {
37 $this->latitude = $lat;
38 $this->longitude = $lon;
39 
40 return $this;
41 }
42 
43 public function applyCondition($query, $input)
44 {
45 // If the user has chose "near", then we're looking for
46 // records less than a certain distance away, so we'll
47 // use the `<` operand.
48 $operand = $input['clause'] === static::CLAUSE_NEAR ? '<' : '>';
49 
50 // Geocode the address (outside the scope of the example).
51 $address = Geocoding::code($input['value']);
52 
53 // https://tighten.co/blog/a-mysql-distance-function-you-should-know-about/
54 $sql = <<<SQL
55(
56 ST_Distance_Sphere(
57 point({$this->longitude}, {$this->latitude}),
58 point(?,?)
59) * .000621371192) $operand ?
60SQL;
61 
62 // Apply to the query.
63 $query->whereRaw($sql, [
64 $address->longitude,
65 $address->latitude,
66 $miles = 5
67 ]);
68 }
69 
70 protected function ensureLatLonConfigured()
71 {
72 if (!$this->latitude || !$this->longitude) {
73 throw new ConfigurationException(
74 'Latitude and longitude attributes must both be configured.'
75 );
76 }
77 }
78}
Code highlighting powered by torchlight.dev, a Hammerstone product.

Using the Condition

Now that you've built your custom condition you can use it in any filter you want:

1public function conditions() {
2 return [
3 DistanceFromAddressCondition::make('branch_location')
4 ->latlon('store_lat', 'store_lon')
5 ];
6}

and your user will be presented with: [Branch Location] [Is Near] [User entered address].

Hopefully this example shows you how powerful and flexible custom conditions can be to meet any specific needs you might have.