php - Change charset in Laravel

730

Is there a way to change the default charset (UTF-8) to ISO-8859-1 in Laravel Framework?

I already tried:

Adding headers to routes;

$headers = array("Content-Type: text/html; charset=iso-8859-1");
Route::get('/notificacao/nova','[email protected]', $headers);
788

Answer

Solution:

I had your same problem and solved it adding a middleware which replaces UTF-8 with ISO-8859-1 in the Content-Type charset header.

I created a new middleware class, namedCharsetMiddleware, with these contents:

namespace App\Http\Middleware;

use Closure;

class CharsetMiddleware
{
    public function handle($request, Closure $next)
    {
        $response = $next($request);
        $contentType = $response->headers->get('Content-Type');
        if (!empty($contentType)) {
            $response->header('Content-Type', str_replace('UTF-8', 'iso-8859-1', $contentType));
        }
        return $response;
    }
}

I put it in app/Http/Middleware/ folder, and then in app/Http/Kernel.php class added the class reference at the end of$middleware array property, like this:

protected $middleware = [
    // ... Other middleware references
    \App\Http\Middleware\CharsetMiddleware::class,
];

People are also looking for solutions to the problem: Error: Illegal characters found in URL php api script

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.