Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return a json error in middleware?

Tags:

laravel-5

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?

like image 853
chii Avatar asked Mar 29 '17 07:03

chii


2 Answers

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.

like image 159
chii Avatar answered Oct 12 '22 04:10

chii


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 middleware
must 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

like image 37
Francesco Taioli Avatar answered Oct 12 '22 03:10

Francesco Taioli