Minify HTML in Laravel Using middleware

Hello LaraDevs !

While writing HTML markup we put lots of blank space for code readability and and indentation. Web browsers do not read our code in that way, It just put them in single line. It does not care about the indentations. These blank space use extra disk space and increase our page loading time of our application.

Minifying HTML will definitely helps on speeding up our application by reducing the file size. There are different approaches to minify HTML and Laravel has bunch of different packages for minify HTML, CSS and JS. But here I am talking about HTML only and will show you how to minify it without any package. So in this tutorial I will show you how to unify/minify HTML in our Laravel application, with very few steps.

We Can easily minify HTML using Laravel Route Middleware . Lets follow the steps below.

Make a Middleware

Run the following artisan command:

php artisan make:middleware HTMLmin 

Above command will make a middleware inside App\Http\Middleware called HTMLmin.php

Open that file and put following code inside the file.

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class HTMLmin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $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);
    }
} 

Register the middleware

Now its time to register our middleware. Open App\Http\Kernel.php file and inside the protected $routeMiddleware array put our new middleware as follows:

 /**
     * The application's route middleware.
     *
     * These middleware may be assigned to groups or used individually.
     *
     * @var array
     */
    protected $routeMiddleware = [
    	....,
    	....,
    	....,
        'HTMLminify' => \App\Http\Middleware\HTMLmin::class
    ]; 

Using the Middleware

To use our middleware lest open our route.php file or any other route file and apply the middleware in the routes. you can group them or use individually. Both way, it will minify our HTML and boost application speed.

// Group middlware
Route::group(['middleware'=>'HTMLminify'], function(){ 
  
  Route::get('/', [PageController::class , 'index']);
  Route::get('/{slug}', [PostController::class, 'show');
  ...
  ...

});
 
  
// Applying Middleware individually in routes
 Route::get('/category/Laravel', [CategoryController::class, 'showByCategory'])
                         ->middleware('HTMLminify'); 

Summary

In above example we are simply searching white spaces in our html markup or in our page and removing these. Doing this will reduce file size and speed up the application by some factor. While talking about page speed there are also other things to take care of, like CSS and JS minifying.

Hope this article will speed up your application by some factor. If you have any question, leave in the comments below.

Comments :

  • allen khawas 4 months ago

    Thanks. Write a post also for css and js bundling.