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.store', ['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;
	server_name www.example.com;
	root /var/www/example/;

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

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

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

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.

Using AWS Cloudfront with a Custom Domain and Free SSL

AWS Cloudfront is a CDN for delivering content to your users faster, by serving it from locations closer to them. It caches requests nearer to users and call pull the original content from its S3 service, or your own web server.

By default a Cloudfront distribution comes with an SSL enabled subdomain on the cloudfront.net domain name that looks something like this:

dlksg932809.cloudfront.net //default example
cdn.mikehealy.com.au //custom domain

You can also create a free SSL certificate through AWS for your own custom domain (or subdomain) and point that to your Cloudfront distribution. This is especially useful if you’re using Cloudfront to serve a static site in lieu of a conventional server.

Creating a Free, Custom SSL through AWS Certificate Manager

Go to AWS’ Certificate Manager product and choose ‘Request a certificate’.

You’ll be asked to specify your domain (or subdomain) and which validation method to use.

DNS Validation

This method has you setting a CNAME record for the domain to prove that you have control of the domain. It’s the preferred method, however some DNS providers don’t support the characters required due to faulty validation rules, and so it might not be available to you.

Email Validation

This is the alternative method and requires you to have access to receive mail at a common admin email address such as administrator@example.com for your root domain.

The process after either creating your DNS CNAME or selecting email validation is essentially to follow the prompts and let AWS provision a new certificate for you.

Setting up your Cloudfront Distribution

Once your certificate has been created you can create your new distribution and select it as the SSL certificate to use. The other options for your distribution aren’t covered in this post, but you can now use your own (sub)domain to point to this distribution and your choice of S3 or your own web server to act as the origin server.

Provisioning the distribution takes a little while, usually more than 15 minutes in my experience.
Once that’s happened you’ll have a great, low cost static file serving distribution on your own domain with free SSL!

This is great for low-cost side projects or serving static files for your main website that would not otherwise justify setting up a web server and configuring Lets Encrypt, or having to purchase a traditional SSL certificate.

CDNs for WordPress

You can use a plugin (of course) to rewrite your content URLs so they are served off your CDN. This leaves the editing and publishing process unchanged. The plugin will handle converting local URLs to CDN versions.

As mentioned you have the choice of using your local web server, or S3 as the origin for your Cloudfront distribution. One advantage of moving your media off your WordPress site and onto S3 as the main store is that your local site install stays smaller and is therefore easier to move and backup.

Useful WordPress / S3 / CDN plugins

WordPress HTTP Error Uploading Larger Files

Sometimes WordPress shows a mysterious “HTTP Error” after attempting to upload a file. The file appears to upload with the progress sliders moving as normal, but fails at the end of the process without a descriptive error message.

There are a few possible causes of this, but if you have an Nginx server and small uploads are working while larger ones fail the problem might be Nginx’s max body size setting.

Increase Nginx’s client_max_body setting

Go to your Nginx sites-enabled directory (/etc/nginx/sites-enabled on Ubuntu systems) and update your server settings like so:

server {
   # other stuff is here too

   client_max_body_size 20M;

Restart Nginx.

Laravel Eloquent gotcha using With and Find

The Eloquent ORM in Laravel makes it easy to pull in related models using the ::with() method.  It’s very useful and can solve the N+1 Query problem that can occur when accessing related models in a loop from the parents records.

$data = MyParentModel->with('ChildModel');

You’d commonly want to use this when accessing a particular parent model using the ::find() or ::findOrFail() method. The trap can be that with() must be called before findOrFail().

If you chain methods and call findOrFail() first it will be ignored and your result set will include all parent rows!

$data = MyParentModel->with('ChildModel')->findOrFail($parent_id);