Digitlimit Digitlimit - 6 months ago 55
PHP Question

How do I compress HTML in laravel 5

In Laravel 4.0, I use the code below to compress the HTML laravel response outputs to browser, however it doesn't work in laravel 5.

App::after(function($request, $response)
{
if($response instanceof Illuminate\Http\Response)
{
$buffer = $response->getContent();
if(strpos($buffer,'<pre>') !== false)
{
$replace = array(
'/<!--[^\[](.*?)[^\]]-->/s' => '',
"/<\?php/" => '<?php ',
"/\r/" => '',
"/>\n</" => '><',
"/>\s+\n</" => '><',
"/>\n\s+</" => '><',
);
}
else
{
$replace = array(
'/<!--[^\[](.*?)[^\]]-->/s' => '',
"/<\?php/" => '<?php ',
"/\n([\S])/" => '$1',
"/\r/" => '',
"/\n/" => '',
"/\t/" => '',
"/ +/" => ' ',
);
}
$buffer = preg_replace(array_keys($replace), array_values($replace), $buffer);
$response->setContent($buffer);
}
});


Please how do i make this work in Laravel 5.

OR

Please provide a better way of compressing HTML in laravel 5 if any.
Thanks in advance.

NB: I don't wish to use any laravel package for compressing html, just need a simple code that does the work without killing performance.

Answer

The recommended way to do this in Larvel 5 is to rewrite your function as middleware. As stated in the docs:

..this middleware would perform its task after the request is handled by the application:

<?php namespace App\Http\Middleware;

class AfterMiddleware implements Middleware {

    public function handle($request, Closure $next)
    {
        $response = $next($request);

        // Perform action

        return $response;
    }
}
Comments