Skip to content

Instantly share code, notes, and snippets.

@shankar-bavan
Created December 25, 2022 14:15
Show Gist options
  • Save shankar-bavan/77ae124556fa5e9c50277cdf4b00e4a8 to your computer and use it in GitHub Desktop.
Save shankar-bavan/77ae124556fa5e9c50277cdf4b00e4a8 to your computer and use it in GitHub Desktop.
Laravel HTML minification

Run the command to make HTML minify middleware and do the code in the middleware for unifying the HTML on-page request.

php artisan make:middleware HtmlMinifier
<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Response;

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

        $contentType = $response->headers->get('Content-Type');
        if (strpos($contentType, 'text/html') !== false) {
            $response->setContent($this->minify($response->getContent()));
        }

        return $response;

    }

    public function minify($input)
    {
        $search = [
            '/\>\s+/s',
            '/\s+</s',
        ];

        $replace = [
            '> ',
            ' <',
        ];

        return preg_replace($search, $replace, $input);
    }
}

Add the middleware into kernel.php file into the $routeMiddlewareGroup

protected $routeMiddleware = [
  'HtmlMinifier' => '\App\Http\Middleware\HtmlMinifier',
]

Now we can use this middleware in our route file. For every request on our site, this middleware will automatically do HTML modification and response to the user.

Route::group(['middleware'=>'HtmlMinifier'], function(){ 
  
  Route::get('/', 'SiteController@home');

});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment