How to define route filters

I’m not sure what the custom collection filter is, but from what I’ve read, it’s not exactly what I’ve done.

I’m coming from the laravel world - and one of the things they have is the concept of middleware - its functions that run when the routing happens.

For me what you just created is a global middleware. (controller that runs before the main controller).

Now in kirby we already have something like that. one you define a route. with a “filter” before it. for example:

    'pattern' => '/',
    'action'  => 'DashboardController::index',
    'filter'  => array('auth', 'isInstalled'),

But I can’t find anywhere to define new “filters” (or middleware) for routes… or globally.
I know kirby is a lighter CMS in comparison with the Laravel app framework thing. but it would make life easier sometime (like for the unpublished thing). and this is why I love it for building websites.

anyway, I’m sorry I’m hijacking you post. I was just thinking about this today, and your precontroller made me say it out loud.

You can define filters like this:

kirby()->router()->filter('auth', function() {
  // Stop execution or redirect if your custom rule matches
1 Like


is there a reference for this in the documentation? I was looking and couldn’t find.

Not currently. These more complex and advanced features are not all documented. I have added it to our list however.

1 Like

Ok, so this doesn’t actually work :frowning:

I put

kirby()->router()->filter('auth', function() {
   if(! $site->user()->isAdmin()){

in my plugin, and it gave me the next error

Fatal error: Call to a member function filter() on null in C:\wamp64\www\plainkit\site\plugins\userManager\Routes\routes.php on line 7

It seems to me that the router isn’t yet defined when the plugins are called, but everything else user made that get’s run is run after the routing happens.
So unless I’m wrong, this is actually impossible to do?

You are right, the router is started after the plugins are loaded, otherwise you wouldn’t be able to define routes from plugins.
A filter is just a function that is called before the route is run, so you should be able to get a similar result by defining the code as a function in your plugin and calling that function at the start of each route action.

yea, I get that…

but, I’m setting up a good amount of routes so I was hoping I could do it more aesthetically.

I’m going to make it as a feature request for kirby. Where would I do that?


If you have a lot of routes, it might make sense to use your own router instance. You can then use filters with it. There is an example in this topic:

Ok makes sense, I was just trying to “keep convention” with other things I do, and use the extension registry for this.