I created a dribble clone using Laravel 8 and Nuxt.js. Since I won't be using the web route so I decided to create a global JsonRequestMiddleware that accepts headers as application/json. This write-up aims to show you how I implemented that step by step. Happy reading
Step 1: create a new middleware
php artisan make:middleware JsonRequestMiddleware
Step 2: Copy this code and place it inside the JsonRequestMiddleware at the handle method before 'return $next($request);'
$request->headers->set("Accept", "application/json");
Your end result should look like this:
public function handle(Request $request, Closure $next)
{
$request->headers->set("Accept", "application/json");
return $next($request);
}
Step 3: Go to App\Http\Kernel.php file and add the code below at global HTTP middleware stack.
protected $middleware = [
\App\Http\Middleware\JsonRequestMiddleware::class,
// Other Middleware::class comes after...
];
Step 4: clear the application config cache and dump-autoload
php artisan config:cache or composer dump-autoload
you can share with me if you have got a better way of achieving this. I hope this is helpful. Thanks.
Top comments (7)
"Since I won't be using the web route so I decided to create a global JsonRequestMiddleware.... " It works great even when the app has web route (it does not affect the web route) - IFF you add it to protected
instead of
$middleware
in the Kernel.php fileThank you for your feedback
Shouldn't this
\App\Http\Middleware\JsonMiddleware::class,
be\App\Http\Middleware\JsonRequestMiddleware::class
instead?That's a very good observation from you, I have updated that. Thank you so much.
This was really helpful. Saved me a lot
Thank you for your feedback
Shouldn't this
\App\Http\Middleware\JsonMiddleware::class
be \App\Http\Middleware\JsonRequestMiddleware::class instead?Some comments have been hidden by the post's author - find out more