laravel json response utf-8 code example

Example: laravel json utf-8

//Create this middleware below:

class JsonUtf8Middleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        $data =  $next($request);
        if($data instanceof JsonResponse) {
            $data->withHeaders(['Content-Type' => "application/json; charset=utf-8"]);
            $data->setEncodingOptions(JSON_UNESCAPED_UNICODE);
        }

        return $data;
    }
}
/**
 * It will set content-type application/json with charset UTF-8 (line 16). 
 * If you want UTF-8 serie, you want to apply UNICODE.
 * By default, the responde will scape UNICODE, 
 * replacing accented words for example.
 * So, that why this middleware will unscape unicode at (line 17)
 * Don't forget to configure it App\Http\Kernel.php!
*/

Tags:

Php Example