Skip to content

Instantly share code, notes, and snippets.

@allaniftrue
Last active March 16, 2019 19:00
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save allaniftrue/9113258 to your computer and use it in GitHub Desktop.
Save allaniftrue/9113258 to your computer and use it in GitHub Desktop.
Laravel Minify HTML response
<?php
/*
* An improvised Gist from
* https://gist.github.com/zmsaunders/5619519
* https://gist.github.com/garagesocial/6059962
*/
App::after(function($request, $response)
{
if(App::Environment() != 'local')
{
if($response instanceof Illuminate\Http\Response)
{
$output = $response->getOriginalContent();
$filters = array(
//Remove HTML comments except IE conditions
'/<!--(?!\s*(?:\[if [^\]]+]|<!|>))(?:(?!-->).)*-->/s' => '',
// Remove comments in the form /* */
'/(?<!\S)\/\/\s*[^\r\n]*/' => '',
// Shorten multiple white spaces
'/\s{2,}/' => '',
// Collapse new lines
'/(\r?\n)/' => '',
);
$output = preg_replace(array_keys($filters), array_values($filters), $output);
$response->setContent($output);
}
}
});
?>
@pvos
Copy link

pvos commented Jul 15, 2014

Thank you for the effort, this will break blade and has several issues with queries printed in the view instead.

@facegit
Copy link

facegit commented Jul 15, 2014

This looks awesome, but how do I include it into my project? I'm using a open source laravel 4 project, and I do not have a lot of experience with neither php or laravel. Thanks for helping me! :)

@allaniftrue
Copy link
Author

You can add it up on the filters.php file

@allaniftrue
Copy link
Author

@pvos, thanks for the warning but I have used it on my blog which is developed using Laravel but seemed to work fine. No issues so far and yes I'm using blade templates. Can you show an example pls?

@SasSam
Copy link

SasSam commented Sep 17, 2014

if I use it with the last rule (/(\r?\n)/) the output generates an empty (0 byte) output for sitemap generator robot. I use xml-sitemaps.com for it. Check it with http://www.xml-sitemaps.com/se-bot-simulator.html (with Googlebot option).

If I remove this rule, everything will be fine. Any idea?

@allaniftrue
Copy link
Author

Can I know the site? Because mine has no problem

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