Ben Furfie

Accessing controller methods on the front end in Statamic

Erin Dalzell revealed a neat little trick you can use with controllers in Statamic in the Discord channel. Rather than letting it slip away into the ether, I thought I'd jot it down here.

Published May 17th 2019

It's possible to access controller routes within Statamic in the front end. To show how this works, let's create a new controller addon. For the sake of making it more realistic, let's work with the example James in the Discord channel wanted to use. That usecase was for integrating Recaptcha into his Statamic site.

Either spin up a new Statamic site or cd into an existing site. Then run:

php please make:controller Recaptcha

You'll find your new controller in: /sites/addons/Recaptcha/RecaptchaController.php;

Let's change the index() method to getMessage().

Then, within the method, change return $this->view('index'); (which would return a view called index) to return 'You found my secret message!';.

If you then go to your Statamic site and then visit /!/Recaptcha/message (i.e.!/Recaptcha/message) you should see 'You found my secret message' in your browser.

How it works

Controllers in Statamic automatically generate routes for any method prefixed with get. That means that by planning how you are going to name your methods in advance, you can save yourself a lot of leg work.

This sort of thing can be really useful for when you need to send a form to a specific controller endpoint to check a Recaptcha token matches up (for example).

If you want any more examples, like this, ping me on Twitter.