Laravel 5: create route group that is only available during testing (Middleware)


Today I needed to protect a group of routes from everything except my testing environment. I need to run PHPUnit tests that depend on certain routes, but I don’t want those routes to be available anywhere else. I’ll share in this blog post what I did to get what I need.

Assumptions in this tutorial:

You already have Laravel 5 installed on your computer and you are running the app in “testing” mode (e.g. PHPUnit testing)

Introduction

In Laravel, Middleware filters requests that are coming into our application. One of the pre-made Middleware in Laravel 5.2 is Authenticate, which looks like this:

Inside the handle() method, it checks if the request is using AJAX -or- is asking for JSON, and if either condition returns TRUE, it blocks access and returns ‘Unauthorized’ as response. Otherwise, client is redirected to the ‘login’ route, which should happen when client is requesting via web browser.

What I did to make my grouped routes available only in testing environment (in my case, when running PHPUnit) was create a new Middlewave. I’ll show you how. 🙂

Create a new file under Http/Middleware and name it TestingEnvOnly.php

In the handle method, we check if app environment is set to testing, and if so, we allow the request to access the requested route. Otherwise, the request should fail and repond with ‘Unavailable’.

Now, let’s register this Middleware to Http/Middleware. Add the following to the $routeMiddleware array:

It’s time to add a testing-only route:

If you use PHPUnit like I do, you can test our new Middleware by creating this test method:

I’m only using var_dump so that we can easily see the printed string response which should say “This should be visible only for testing environment” when you run PHPUnit.

Now, in your web browser, visit the route your set for /api/v1/testing_env_only. It should say ‘Unauthorized’.

Here’s how the files I edited in Laravel look like now:

I’m using Laravel 5.2 and these are codes I uploaded at Gist

Catzie

A Filipino who is a mobile & web developer on weekdays, and a baker on weekends. When I have time to spare, I blog, play video games, watch series (usually anime), cook dishes, draw, or spend a little time with pets. When I have the rare luxury of time, I get to travel and record song covers too! Follow on Twitter: @catzie

Leave a Reply

Your email address will not be published. Required fields are marked *