This will be a short tutorial on how to manage incoming requests to your API and save the request and response data from it.

Let’s kick things of with creating the migration:

php artisan make:migration create_api_entries

And add couple of things to the table:

class CreateApiEntriesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('api_entries', function (Blueprint $table) {
            $table->id();
            $table->string('url')->nullable();
            $table->string('http_method')->nullable();
            $table->string('status_code')->nullable();
            $table->json('request_body')->nullable();
            $table->json('response_body')->nullable();
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('http_requests_logs');
    }
}

After that we will create the middleware class:

php artisan make:middleware ApiEntriesLoggerMiddleware
use Closure;
use Illuminate\Http\Request;
use Shippii\Models\ApiEntries;
use Illuminate\Http\JsonResponse;

class ApiEntriesLoggerMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        return $next($request);
    }
}

And register it in the Kernel -> Http/Kernel.php

protected $routeMiddleware = [
    'apiLogger' => ApiEntriesLoggerMiddleware::class
];

Create a Laravel Model for it:

php artisan make:model ApiEntries

And finally inside the ApiEntriesLoggerMiddleware, add the “terminate” method and have fun saving all the information you need.

public function terminate($request, $response)
{
   ApiEntries::create([
      'url' => $request->fullUrl(),
      'http_method' => $request->getMethod(),
      'status_code' => $response->getStatusCode(),
      'request_body' => json_encode($request->all(), true),
      'response_body' => $response->getContent()
   ]);
}

Leave a comment

Trending