Testing Form Request Validation in Laravel

I recently got stuck writing a test for a Controller which uses a custom form request for validation and authorization. Though the form request worked correctly for real requests in the browser, it was being ignored from the Feature test. In other words the Controller action would run even with invalid test input and even when the form request was hard-coded to specifically block authorization.

Incorrect Approach

I had been creating the form request, instantiating the Controller I wanted to test and sending the request. This bypassed the checks, presumably because the middleware that triggers validation isn’t run in this context.

function test_invalid_request()
  $request = CafeStoreRequest::create('cafe', 'POST', ['cafe_name' => '']); //should fail
  $controller = new App\Http\Controllers\CafeController();
  $response = $controller->store($request);


What Worked

Instead of manually creating a controller, I needed to route the request through the HTTP layer so that the middleware would do its thing and trigger the appropriate error.

function test_invalid_input()
  $response = $this->post(route('', ['cafe_name' => '']));

Create a Light & Dark Mode Control with Tailwind & Alpine

Some users prefer darker colour themes to prevent eyestrain, while others like having the choice depending on their lighting conditions. Tailwind makes it easy to specify different colours to use depending on which mode is active.

By default Tailwind responds to the prefers-color-scheme media query, which passes through the users’ operating system preference. You can also configure it to alter the colours by inheriting a ‘dark’ CSS class name from a parent element. This lets you to build your own UI control to switch modes, so that users can have a different preference for your site than their OS.

To do this, change the darkMode property in your tailwind.config.js file

// tailwind.config.js

module.exports = {
  darkMode: 'class',

Controlling The Active Mode

Now that Tailwind is configured to compile dark mode colours based on the .dark class name, we need a way to toggle that class name. We also need to persist the selection between sessions and page loads.

I’ll be using localStorage to store the user’s preference and AlpineJS to handle the toggling action. Alpine is a lightweight JS framework that works with your markup and doesn’t require a build step.

As well as storing the user’s preference we’ll need to apply it as early as possible during page rendering to activate their desired mode.

How it Works

  • Tailwind generates classes that are applied when dark mode is activated
  • When our page loads we see if the user has set an explicit choice of mode for our site (using the UI control we provide)
  • If they’ve asked for dark mode we apply the CSS class
  • If they have not set a preference, but their implicit preference via their OS is for dark mode we apply the CSS class
  • Otherwise we’ll fall back to the default light mode

When our user makes a specific choice using the on-page UI we’ll update the document class and also save their preference in localStorage for subsequent page loads.

UI Control

Here’s the code to provide light & dark mode buttons. Alpine uses the x-data property to store the state for our component. x-init runs on setup and syncs our local state with what was previously stored in localStorage.

      mode: '',
      setColorMode: m => {
          if (m === 'dark') {
              localStorage.setItem('colorMode', 'dark')
          } else {
              localStorage.setItem('colorMode', 'light')

  x-init="() => {
      const m = localStorage.getItem('colorMode');
      if (m !== 'dark' && m !== 'light') return;
      mode = m;
    @click="mode='light'; setColorMode('light');"
    :class="{'font-bold': mode === 'light', 'font-thin': mode !== 'light' }"
    class="underline px-2 py-1 rounded-md border-white hover:bg-gray-100 dark:hover:bg-gray-800"
    @click="mode = 'dark'; setColorMode('dark');"
    :class="{'bg-gray-700 text-gray-200 border border-solid border-gray-600 font-bold': mode === 'dark', 'font-thin': mode !== 'dark' }"
    class="underline px-2 py-1 rounded-md hover:bg-white dark:hover:bg-gray-800"

Persisting The Selection

Of course as users browse around your site you don’t want them to have to re-apply their choice of colour mode every time they visit a new page. We’ll use a bit of JS near the top of our document to reapply their preference as early in the render as possible.

  <!-- other bits -->
  <link rel="stylesheet" href="css/style.css" type="text/css">
  <script src="detect-mode.js"></script>
// detect-mode.js
// set initial color scheme

let explicitelyPreferScheme = false
if (window.localStorage) {
    if (localStorage.getItem('colorMode') === 'dark') {
        explicitelyPreferScheme = 'dark'
    } else if (localStorage.getItem('colorMode') === 'light') {
        explicitelyPreferScheme = 'light'

if (explicitelyPreferScheme !== 'light' && window.matchMedia('(prefers-color-scheme:dark)').matches) {

This will apply dark mode if our visitor has selected it from the UI control above; or if they have not set any preference but their OS is set to use dark mode.

Live Demo

You can change your preference and reload this page to see it persist.

Enjoy the darkness!

Fixing Curl Error 35 with WordPress API calls

I recently had an issue where a WordPress website I was building could not connect to itself for wp-cron or background tasks.

This was the error:

curl: (35) error:1408F10B:SSL routines:ssl3_get_record:wrong version number

It turns out I had a faulty nginx configuation, and the server block was missing the ssl directive. The certificates worked in both Chrome and Firefox without warnings, but they weren’t doing what the needed to for curl to work.

server {
	listen 443 ssl;
	root /var/www/example/;

Adding ssl to the listen line fixed the cURL error and wp-cron

Confirm Before Deleting WordPress Trash

I recently watched someone who using their phone and tablet for everything manage posts on their WordPress blog. One they intended to keep ended up in the Trash by mistake. Restoring it is easy enough, but the ‘Restore’ and ‘Delete Permanently’ links are very close to each other on a mobile screen and I got a little nervous seeing them tap restore 30px away from the kill button.

I’ve created a simple WordPress plugin that adds a confirmation step in the admin area before deleting or emptying the Trash.

It’s a pretty simple thing, just a little JavaScript to make sure the click was deliberate. Give it a go if you’d rather have an extra click than possibly try and recover a post from a site backup.

Download the Plugin

Trash Fail Safe for WordPress.

Deleting with Axios and Laravel

With a RESTful Controller you will typically have methods to show, list, update, edit and destroy (delete) the entity in question. The controller methods map to HTTP methods (verbs) such as GET, POST, PUT and DELETE.

Not all browsers support all of the HTTP methods. The PUT and DELETE requests might actually be sent as a POST request, but with the _method parameter included to tell Laravel’s routing system what to do with the request. When that hint is present Laravel will use it to determine the type of request, rather than the actual HTTP request method.

If you are making these HTTP requests with Axios then you might find some of the calls are failing with a 405 Method Not Allowed error.

This is due to the way Axios sends POST, PUT and DELETE requests. You may need to actually POST the request and include the _method hint in the request data instead.

Example JavaScript'/myentity/839', {
  _method: 'DELETE'
.then( response => {
   //handle success
.catch( error => {
   //handle failure

Save-Data for Low Bandwidth Users

Everyone likes a fast website, but some users have connections and data plans that make it especially critical. Some browsers support a ‘saves-data’ setting which sends an HTTP header along with requests that the server can use to respond with a lighter weight page.

In mobile Chrome this is called ‘Lite Mode’. Desktop browsers can also enable the setting via an extension. Turning the setting on doesn’t necessarily do much on its own, but it does however give the server a chance to make its own aggressive optimisations knowing the user is on board.

To help low-bandwidth users have a good time websites can detect the header and avoid serving unnecessary assets such as custom fonts or background images and videos.

I’ve created a few save-data customisations here on my site. When the WordPress functions.php file detects this setting it doesn’t enqueue the custom fonts stylesheet from Google Fonts. I’m also using slightly different styles to drop the decorative background image from the masthead.

You can see the difference here:

The setting can be detected server-side by looking for a HTTP header (save-data=on) or client side in JS to set a flag for your CSS selectors.


function saveData(): bool {
   return ( isset($_SERVER["HTTP_SAVE_DATA"]) &&
      strtolower($_SERVER["HTTP_SAVE_DATA"]) === 'on' 
//JS example (courtesy of Nooshu)
//add save-data class name to document element for CSS selectors
if ("connection" in navigator) {
    if (navigator.connection.saveData === true) {

Exactly what you do with save-data is up to you. Nothing is automatic, so it’s up to the website to determine what can be changed to better serve those users. It just gives you a clear hint at the user’s preference about bandwidth usage.

Enabling Gutenberg for Custom Post Types

Super quick tip here, but probably non-obvious.

If you want to be able to use WordPress’ Gutenberg editor with a Custom Post Type you’ll need to register the post type with REST API support.

register_post_type('my_post_type', [
    'label' => 'Things',
    'labels' => ['...'],

    'show_in_rest' => true, //required to enable Gutenberg editor

Laravel’s Signed URLs Breaking with Nginx

Laravel includes a feature to sign URLs so that publicly accessible routes can be visited knowing the query string hasn’t been tampered with.

Laravel uses this for email verification links by default. I ran into a problem where signed URLs were always failing (throwing the 403 exception) in my production environment. The same code worked locally.

In turns out that this was a result of the way the package uses query string parameters to build the signature. My production nginx configuration was creating a different parameter signature to what Laravel was expecting. This was fine for unsigned URLs as the routing still worked, but it did mean that the ‘signed’ middleware would always fail.

The solution was just to alter my sites nginx config like this:

# Nope
try_files $uri $uri/ /index.php?q=$uri&$args;

# Yes
try_files $uri $uri/ /index.php?$query_string;

Now Laravel’s request object receives the same query parameters and the signed URL signature will match.

CDNs for Small Websites

Content Delivery Networks (CDN) are typically most useful for sites with a widely dispersed audience, or those with high traffic. They serve static files from locations close to the user for faster response times and alleviate load from the main server. However a CDN can make small websites at the other end of the spectrum a lot faster too!

CDNs for small websites

I recently built a simple one-page website for a client. It’s a minimal online presence to capture searches for their business name, provide some information and a contact form.

In theory even entry-level shared hosting should load a site like this very quickly. In practice it can be like a ballpoint pen – if it hasn’t been used for a while it’s slow to put ink on the page. Once it gets going it’s fine.

Low-traffic small business sites can effectively be ‘put the site at the back of the server’, like the ink that’s dried on the tip of a pen. If the site hasn’t been requested for several hours that first response can be a lot slower than it should be. Subsequent hits might be perfectly quick, but that doesn’t help with the first impression.

I was able to speed up this site considerably by using the traditional cPanel shared host as a CDN Origin, and route the domain through Cloudfront. Cloudfront acts as a fast cache, storing a rendered version of the page (and its supporting files) to respond quickly to sporadic visits.

This retains the flexibility of some basic server side rendering while massively speeding that first page load. The backend functionality required to run the contact form works via an Ajax request to the underlying cPanel server.

For simple sites this approach was a lot easier to develop (read cheaper) than a full static site generation approach, while still giving some scripting capabilities and the speed of a static site deployed to a CDN.

WordPress 5.0 and the Gutenberg High Drama

Considering how widely used and how widely extended WordPress is, it’s renowned for its backwards compatibility with new releases. The next major WordPress update – v5.0 – is due for release in a couple of days amid a shroud of hot drama over the stability of the new Gutenberg editor.

Gutenberg is a major redesign in the way Pages and Posts can be constructed within WordPress. It brings the concept of custom ‘Blocks’ which allow chunks of information to be presented in specific ways. Conceptually this approach has widespread support, but retrofitting it into the existing WordPress ecosystem is a challenge. The team have put a lot of effort into backwards compatibility, but it’s a complex process and there are widespread doubts about how smoothly that will go.

Knowing this the WordPress development team have been distributing a WordPress Classic Editor plugin to allow sites to keep the old editor with the new version of WordPress.

My advice would be for anyone updating an existing WordPress site is to first install and activate this plugin, and to only use the new Gutenberg editor once they’ve been able to test it on a staging version of their website. Gutenberg may well work fantastically with your theme and plugins, but it’s far from guaranteed and you don’t want to be trying it out in production!