Log Your Laravel API Routes With Middleware

I am a full-stack web developer that enjoys coding in Laravel and React.
Search for a command to run...

I am a full-stack web developer that enjoys coding in Laravel and React.
No comments yet. Be the first to comment.
Here I will post some articles that help devs with simple and complex topics in Laravel.
In many tutorials around the web, authors use and define services like Twilio in the controller, which flies in the face of the principles of MVC frameworks like Laravel. It also doesn't heed DRY principles as defined in the book, The Pragmatic Progr...
Switching stacks

If you don't know what Twin Macro is, check it out! It's a great library that blends Tailwind CSS and Styled Component systems, like Emotion. I love using Twin because it lets me use Tailwind while separating my styling from my markup and methods. If...

Many developers know that full-stack apps with a Vue frontend can be quickly spun up with Laravel Jetstream. What many don’t know is that recently, the Laravel team made it easy to make an Inertia app with Laravel Breeze. In this article, we'll make ...

Extending the Rule Object with a DateTime Trait

Using Custom Console Commands

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:
php artisan make:middleware LogRoute. This will create a file in app/Http/Middleware.The Meat:
use Illuminate\Support\Facades\Log at the top of your file.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)
...
}
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()
];
Log::info(json_encode($data));
}
return $response;
}
Finishing Up:
$routeMiddleware. When you're there, add this line: 'log.route' => \App\Http\Middleware\LogRoute::class,. ->middleware('log.route') at the end of the route that you want to test.The End:
One More Thing:
$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.