Skip to content

Instantly share code, notes, and snippets.

@denniseilander
Last active June 11, 2021 12:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save denniseilander/ca32c8bde3a4f102cc51ab8a70265237 to your computer and use it in GitHub Desktop.
Save denniseilander/ca32c8bde3a4f102cc51ab8a70265237 to your computer and use it in GitHub Desktop.
Force http requests and responses as json output. When making requests to an endpoint, there is no need to add the Content-Type and Accept application/json headers anymore.
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Auth\Middleware\Authenticate as Middleware;
class AsJson extends Middleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle(Request $request, Closure $next)
{
$request->headers->set('Accept', 'application/json');
$request->headers->set('Content-Type', 'application/json');
return $next($request);
}
}
@denniseilander
Copy link
Author

You can use this middleware by setting it in the middleware method;

<?php

use App\Http\Middleware\AsJson;

Route::middleware([AsJson::class])->get('/users');

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment