I'm building an app and I'm using laravel5 as webAPI. When the webAPI is in Maintenance Mode, I want to return a json error to app and I will get the status code in app to show a suitable message.
I rewrite the laravel CheckForMaintenanceMode for somereason and registed it in Kernel.
I write
if ($this->app->isDownForMaintenance()) {
$ip = $request->getClientIp();
$allowIp = "111.222.333.444";
if ($allowIp != $ip) {
return response()->json(['error' => "Maintenance!!"], 503);
}
}
return $next($request);
But I can get NOTHING in app side.I cannot get the message, the satus....
I writh the same code like return response()->json(['error' => "errormessage"], 422);
in controller and I can get the message.status.. in app but I cannot do the same thing in a middleware.
why? how to do it?
This worked:
if ($this->app->isDownForMaintenance()) {
$ip = $request->getClientIp();
$allowIp = "111.222.333.444";
if ($allowIp != $ip) {
return response(['Maintenance'], 503);
}
}
return $next($request);
And not register the middleware in Kernel global HTTP middleware but put it in the route(api.php),like:
Route::group(['middleware' => 'maintenance'], function(){******}
I really donot know why but this worked for me.
Full example
public function handle($request, Closure $next)
{
if($request->token == "mytoken")
return $next($request);
else return response(['Token mismatch'],403);
}
Explanation
The response of a middlewaremust be an instance of Symfony\Component\HttpFoundation\Response
so, for return a json, you have to do this
return response(['Token mismatch'],403);
The middleware must be registered in Kernel.php
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With