Filters

Filters in Lightpack are reusable hooks that run before or after a controller action. They are typically used for authentication, authorization, CSRF protection, rate limiting, CORS, and other request/response concerns.

How Filters Work

Usage

Attaching Filters to Routes

// Single filter
route()->get('/dashboard', DashboardController::class)->filter('auth');

// Multiple filters
route()->post('/posts', PostController::class)->filter(['csrf', 'auth']);

Grouping Filters

route()->group(['filter' => ['csrf', 'auth']], function() {
    route()->get('/dashboard', DashboardController::class);
});

Halting or Modifying Requests


Defining Custom Filters

php console create:filter TrimFilter

A filter is a class implementing the Lightpack\Filters\FilterInterface interface:

class TrimFilter implements FilterInterface
{
    public function before(Request $request, array $params = [])
    {
        // Logic before action
    }

    public function after(Request $request, Response $response, array $params = []): Response
    {
        // Logic after action
        return $response;
    }
}

Register your filter alias in boot/filters.php:

return [
    'trim' => App\Filters\TrimFilter::class,
];

Built-in Filters

Lightpack provides many pre-defined filters that you can declare on your route definitions. Below are the built-in filters provided by Lightpack, their aliases, and what they do:

1. auth

Purpose: Restricts access to authenticated users (web or API).

2. guest

Purpose: Restricts access to guests only.

3. csrf

Purpose: Protects against CSRF attacks.

4. cors

Purpose: Handles Cross-Origin Resource Sharing.

5. limit

Purpose: API rate limiting.

6. signed

Purpose: Ensures URL signatures are valid.

7. verifyemail

Purpose: Restricts access to users with verified email addresses.

8. mfa

Purpose: Enforces Multi-Factor Authentication.


Filter Parameters

You can pass parameters to filters via the route definition:

route()->get('/api/data', ApiController::class)->filter(['limit:100,5']);

Best Practices


Summary Table

Alias Description Typical Use/Params
auth Require authentication (web/API) auth:web, auth:api
guest Require guest (not logged in)
csrf CSRF protection on state-changing verbs
cors Add CORS headers, handle preflight
limit Rate limiting limit:60,1
signed Require valid signed URL
verifyemail Require verified email
mfa Enforce multi-factor authentication