Is it possible to use defer
functions on API requests? I can run defer
on my website, but through API is not working at all.
Sample scenario:
// Endpoint accessible through browser https://mywebsite.com/something
public function index(Request $request): void
{
Log::info('Before response sent');
defer(function () {
Log::info('Deferred task executed');
});
Log::info('After response sent');
}
// Endpoint accessible through API request https://mywebsite/api/something
public function search(Request $request): JsonResponse
{
Log::info('Before response sent.');
defer(function () {
Log::info('Deferred task executed.');
});
Log::info('After response sent.');
return response()->json(true);
}
This sample only works when acessing the endpoint through browser. With the API endpoint, by using either tests or Postman, the message Deferred task executed.
is never written.
I tried to create a middleware, applied to the API endpoints, in order to make sure the app is terminated so the defer functions execute, but got no luck.
class EnforceDeferForApi
{
public function handle(Request $request, Closure $next)
{
return $next($request);
}
public function terminate(Request $request, $response): void
{
app()->terminate();
}
}
Any solution?
Solved.
Forgot to add \Illuminate\Foundation\Http\Middleware\InvokeDeferredCallbacks::class
to the array of api
in $middlewareGroups
» file kernel.php