Home > front end >  Terminate method in middleware in laravel
Terminate method in middleware in laravel

Time:09-18

I wanted to define a case if a function return false in a terminate() method in laravel middleware so this is what I did

    $parsedData = $this->parse($request);
    if(!$parsedData){
        dd("hello");
    }

the condition is running fine but when I am calling response it is not showing anything

$parsedData = $this->parse($request);
if(!$parsedData){
            return Response::json(array(
            'success' => false,
            'info' => "error"
        ), 422);
} 
\\ called the Response helper 

am I doing anything wrong in this case?

CodePudding user response:

Please check the below code if work for you

   if(!$parsedData){

        $arr = array(
            'success' => false,
             'info' => "error"
        );
        return response()->json($arr);
}

CodePudding user response:

terminate() in middleware execute AFTER response is sent to browser. If you want to do things with response BEFORE in sends to browser - you must use this constriction:

public function handle($request, Closure $next)
{
    $response = $next($request);
    //do stuff
    return $response;
}

CodePudding user response:

Use like this :

 //use Illuminate\Http\Response;

 if(!$parsedData){
    return response()
    ->json(['success' => false, 'info' => 'error'],Response::HTTP_UNPROCESSABLE_ENTITY);
 }

You can replace Response::HTTP_UNPROCESSABLE_ENTITY with 422 directly

For More : https://laravel.com/docs/5.8/responses#json-responses

  • Related