Laravel 11 Middleware on API routes appending #52363
-
Laravel Version11.19.0 PHP Version8.2 Database Driver & VersionNo response DescriptionI am trying to get a json only out for api routes in Laravel 11. <?php
use App\Http\Middleware\ForceJsonResponse;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__ . '/../routes/web.php',
api: __DIR__ . '/../routes/api.php',
commands: __DIR__ . '/../routes/console.php',
health: '/up',
)
->withMiddleware(function (Middleware $middleware) {
$middleware->api(append: [
ForceJsonResponse::class,
]);
})
->withExceptions(function (Exceptions $exceptions) {
})->create(); Just using append() works, ->withMiddleware(function (Middleware $middleware) {
$middleware->append([
ForceJsonResponse::class,
]);
}) This is applicable for all routes, which i dont want. I would like to know why the $middleware->api(append: []); is not working. Steps To Reproduce<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
class ForceJsonResponse
{
public function handle(Request $request, Closure $next)
{
$request->headers->set('Accept', 'application/json');
return $next($request);
}
} create this middleware, |
Beta Was this translation helpful? Give feedback.
Answered by
VishnuSivadasVS
Aug 2, 2024
Replies: 2 comments 2 replies
-
Route::get('/user', function (Request $request) {
return $request->wantsJson() ? 'true' : 'false';
}); The above code works fine. |
Beta Was this translation helpful? Give feedback.
2 replies
-
My mistake, should have use prepend instead of append in this case. That caused the issue. $middleware->api(prepend:
ForceJsonResponse::class,
); Thanks. |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
VishnuSivadasVS
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
My mistake, should have use prepend instead of append in this case. That caused the issue.
Thanks.