Skip to content

Instantly share code, notes, and snippets.

@garagesocial
Forked from zmsaunders/filters.php
Last active February 6, 2023 04:11
Show Gist options
  • Star 32 You must be signed in to star a gist
  • Fork 13 You must be signed in to fork a gist
  • Save garagesocial/6059962 to your computer and use it in GitHub Desktop.
Save garagesocial/6059962 to your computer and use it in GitHub Desktop.
Laravel Filter Helper - Compress HTML Output & Strip Comments
<?php
### --- Snip --- ###
App::after(function($request, $response)
{
// HTML Minification
if(App::Environment() != 'local')
{
if($response instanceof Illuminate\Http\Response)
{
$output = $response->getOriginalContent();
$filters = array(
'/<!--([^\[|(<!)].*)/' => '', // Remove HTML Comments (breaks with HTML5 Boilerplate)
'/(?<!\S)\/\/\s*[^\r\n]*/' => '', // Remove comments in the form /* */
'/\s{2,}/' => ' ', // Shorten multiple white spaces
'/(\r?\n)/' => '', // Collapse new lines
);
$output = preg_replace(array_keys($filters), array_values($filters), $output);
$response->setContent($output);
}
}
});
### --- Snip --- ###
@rotaercz
Copy link

Learning Laravel. Where do you put this to make it work?

@scoutkirkolson
Copy link

Same question here:
Learning Laravel. Where do you put this to make it work?

@nuqz
Copy link

nuqz commented Mar 13, 2017

@rotaercz @KIrkOlson
In Laravel 4.x you should put it into app\filters.php

In modern Laravel 5.x according to the docs you should put it into middleware (see "Before & After Middleware" section).

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

        // HTML Minification
        ....................

        return $response;
}

@webciter
Copy link

webciter commented Aug 13, 2018

Full Laravel 5.x Middleware to add to your projects, https://github.com/webciter/RemoveExcessWhitespaceMiddleware

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