I just made an JSON API in Laravel. How can I disable providers like Illuminate\View\ViewServiceProvider? #41844
Unanswered
ProteanCode
asked this question in
Q&A
Replies: 1 comment
-
You can create middleware that will force JSON response. <?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\ResponseFactory;
class ForceJsonMiddleware
{
protected $responseFactory;
public function __construct(ResponseFactory $responseFactory)
{
$this->responseFactory = $responseFactory;
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next
* @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
*/
public function handle(Request $request, Closure $next)
{
$request->headers->set('Accept', 'application/json');
$response = $next($request);
//Convert not json responses to json
if(!$response instanceof JsonResponse) {
$response = $this->responseFactory->json(
$response->content(),
$response->status(),
$response->headers->all(),
);
}
return $response;
}
} Then in protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
//YOU CAN INCLUDE IT HERE TO FORCE JSON RESPONSE FOR WEB ROUTES
\App\Http\Middleware\ForceJsonMiddleware::class,
],
'api' => [
// \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\App\Http\Middleware\ForceJsonMiddleware::class,
],
]; |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I am sure I do not need it, but the IgnitionServiceProvider forces me to use it
That provider makes some error pages looks more elegant, but hey, its an API...
Beta Was this translation helpful? Give feedback.
All reactions