Sending Laravel Internal Requests

A class I wrote which allows the sending of internal Laravel requests, use them in your unit tests or in your application logic, they're super fast!

Use Case

Whilst writing a unit test I came across the need to send an internal Laravel request.

I needed to do this for two reasons, one to test the full life cycle of the request, instead of the individual classes that the request would go through, to make sure they all worked together. Two, i needed the test to be fast so I wanted to avoid booting up an entirely new application instance. So I wrote the InternalRequest class.

Register the class within Laravel (I put it in my tests directory since I didn’t need to use it during production), and use it in the following way.

// Sending internal requests from inside symphony command

InternalRequest::request('/api/gateway', 'POST', [
    'payload' => [99, 1],
    'eui' => $gateway->eui,
    'timestamp' => date('Y-m-d\TH:i:s\Z')
namespace App\Services;

use Illuminate\Http\Request;
use Illuminate\Foundation\Application;

class InternalRequest {
    //Make an internal request
     * @param $url;
     * @param $action;
     * @param array $data
     * @return \Symfony\Component\HttpFoundation\Response
      public static function request($url, $action, array $data = [])
        // Create request
        $request = Request::create($url, $action, $data, [], [], [
          'HTTP_Accept' => 'application/json']);
        // Handle the require request and return the response;
        $response = app()->handle($request);
        if ($response->getStatusCode() >= 400) {
          throw new \Exception($response);
        return $response;

The class above finds the route via the url, and the request verb, and handles the request. An exception is thrown if there is a problem in any part of the request. Enjoy!