Mind of Lloyd

Mind of Lloyd

Log Your Laravel API Routes With Middleware

Log Your Laravel API Routes With Middleware

Subscribe to my newsletter and never miss my upcoming articles

Listen to this article

From time-to-time, you will happen upon a problem between your frontend and API that you can't quite see. A dd() in your controller or a console.log() in your frontend just doesn't seem to cut it and the problem seems out of reach. Luckily, Laravel provides you with a way to see the request as it hits your API, and that is through middleware.

First Steps:

  • In your terminal, go to where your project's API is located, and type php artisan make:middleware LogRoute. This will create a file in app/Http/Middleware.
  • If you haven't already, download Postman. It will help you to test your API without having to go through your frontend.

The Meat:

  • In your LogRoute.php, import the Log Facade by typing use Illuminate\Support\Facades\Log at the top of your file.
  • Next, in our handle() function, we'll need to first ensure that our request can pass unimpeded between handlers.
    public function handle(Request $request, Closure $next){
      $response = $next($request)
  • Next, we'll need to tell our Middleware to stop running if our app environment isn't local. We'll do that with an if statement: if (app()->environment('local')).
  • Now we can finish up our middleware by making an array of our request and response and logging that data. Our response is what's most important, as it will have a stack trace to help us debug.

    public function handle(Request $request, Closure $next){
      $response = $next($request);
      if (app()->environment('local')){
          $data = [
              'request' => $request->all(),
              'response' => $response->getContent()
      return $response;

Finishing Up:

  • To use our middleware, we first have to register it. Go to Kernel.php in your app/Http folder and scroll all the way down to $routeMiddleware. When you're there, add this line: 'log.route' => \App\Http\Middleware\LogRoute::class,.
  • Now go to your API routes and place ->middleware('log.route') at the end of the route that you want to test.

The End:

  • Test your API by making a request with Postman.
  • Go to storage/logs/laravel.log to see what's happening.

One More Thing:

  • You can add more methods in your middleware to test requests, such as $request->getMethod() which will tell you the type of request method that hit the API (POST, GET, etc.) and $request->getUri() which will tell you the source of the request.
Share this