Kashish Agarwal
Kashish Agarwal

Reputation: 333

base64 not working in Middleware of Laravel 5.4

My middleware Code:

public function handle($request, Closure $next) {
        $api_headers = getallheaders();
        $error_msg = '';
        $error = 0;
        if (isset($api_headers) && !empty($api_headers)) {
                    
            if (isset($api_headers ['device_id']) && !empty($api_headers['device_id'])) {
            
        } else {
            $error_msg = 'Please send device ID header.';
            $error = 1;
        }
        
        if (isset($api_headers['device_type']) && !empty($api_headers['device_type'])) {
            
        } else {
            $error_msg = 'Please send device type header.';
            $error = 1;
        }
    } else {
        $error_msg = 'Please send headers.';
        $error = 1;
    }
    
    if ($error == 1) {
        return base64_encode(response()->json(['error' => true, 'message' => $error_msg, 'code' => 0]));
    } else {
        return $next($request);
    }
}

I want to convert the JSON to a encoded string and send it as a response. So i used base64_encode to converted it into a string. But it is not working in middleware. I do not know its reason I made a lot of efforts but did not understand what to do. I am also attaching a screenshot of the error. Please help if possible.

enter image description here

Upvotes: 2

Views: 413

Answers (1)

Kurt Friars
Kurt Friars

Reputation: 3764

I dont know what status code you want to respond with, but try:

    $encoded = base64_encode(response()->json([
        'error' => true,
        'message' => $error_msg,
        'code' => 0
    ]));

    return response($encoded, ?response status code?)
               ->header('Content-Type', 'text/plain');

Upvotes: 1

Related Questions