Filters run code before or after a controller — like middleware in other frameworks. Use them for login checks, admin-only pages, CSRF, CORS and more.
Create a filter
php spark make:filter AuthFilter creates a class in app/Filters with two methods:
before($request, $arguments = null)— runs before the controller. Return a redirect or response to stop the request.after($request, $response, $arguments = null)— runs after, and can change the response
Register an alias
In app/Config/Filters.php, add it to $aliases: 'auth' => \App\Filters\AuthFilter::class.
Apply the filter
- On a route:
$routes->get('dashboard', 'Dashboard::index', ['filter' => 'auth']); - On a group:
$routes->group('admin', ['filter' => 'auth'], ...) - With arguments:
['filter' => 'role:admin']→$arguments = ['admin'] - Globally in
Filters.php$globals, or by URL pattern in$filters
Built-in filters
csrf, toolbar (debug toolbar), honeypot, invalidchars, secureheaders, cors and more.
Example
Example — Login and role filters
PHP
<?php
namespace App\Filters;
use CodeIgniter\Filters\FilterInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
class AuthFilter implements FilterInterface
{
public function before(RequestInterface $request, $arguments = null)
{
if (! session('user_id')) {
return redirect()->to('login')->with('error', 'Please log in first.');
}
// ['filter' => 'auth:admin'] -> $arguments = ['admin']
if ($arguments && ! in_array(session('role'), $arguments, true)) {
return redirect()->to('/')->with('error', 'You do not have access.');
}
}
public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
{
}
}
// app/Config/Filters.php -> public array $aliases = [ ..., 'auth' => \App\Filters\AuthFilter::class ];
// app/Config/Routes.php
// $routes->get('dashboard', 'Dashboard::index', ['filter' => 'auth']);
// $routes->group('admin', ['filter' => 'auth:admin'], static function ($routes) { ... });
Guests who open /dashboard are sent to /login. Logged-in users without the admin role are sent to the home page when they open any /admin URL.