256 Kilobytes

How to Automatically Merge and Minify CSS Files in Laravel 5.7

Articles in Frameworks | By August R. Garcia

Published 1 week agoMon, 11 Mar 2019 20:01:31 -0700 | Last update 1 week agoWed, 13 Mar 2019 00:56:13 -0700

This also basically works for PHP in general.

63 views, 0 RAMs, and 0 comments

Choose a CSS minifying function. This function from Datayze combined with this additional function to remove comments works fine. Ideally move the minify_css() function to a helper file [additional guide], although you can just shove it into your HTML head.

<?php
// https://datayze.com/howto/minify-css-with-php.php
function minify_css($css, $remove_css_comments=FALSE){
        $css = preg_replace('/\/\*((?!\*\/).)*\*\//', '', $css); // negative look ahead
        $css = preg_replace('/\s{2,}/', ' ', $css);
        $css = preg_replace('/\s*([:;{}])\s*/', '$1', $css);
        $css = preg_replace('/;}/', '}', $css);

        if ($remove_css_comments)
                $css = remove_css_comments($css);

        return $css;
}

// https://stackoverflow.com/questions/4510518/removing-comments-from-js-css-file-using-php
function remove_css_comments($css) {
        $pattern = '!/\*[^*]*\*+([^/][^*]*\*+)*/!';
        return preg_replace($pattern, '', $css);
}
?>

Put this code between your main layout file's <head> tags:

<?php   // Change this when pushing new updates to live to force the source files to remerge and reminify into an updated master css file.
        $v = "?v=1.7.4"; 

        // Combine all stylesheets into a master file to limit to one HTTP request
        // Always rerun on local/development server; on live, only rerun if version changes
        if ( \Cache::get('last_css_merge') != $v    ||    env('APP_ENV') == "local" ) {

                // Merge CSS files
                $files = [
                        'css-file-1.css'   ,
                        'css-file-2.css'   ,
                        'css-file-3.css'   ,
                        'etcetera.css'     ,
                ];
                $m_css = fopen(  $_SERVER['DOCUMENT_ROOT'] . "/css/master-style.css", "w");
                foreach ($files as $f) {
                        $txt = file_get_contents( $_SERVER['DOCUMENT_ROOT'] . "/css/" . $f );
                        fwrite($m_css, " " . $txt . " ");
                }
                fclose($m_css);

                // Minify the merged output 
                $css   = minify_css( file_get_contents($_SERVER['DOCUMENT_ROOT'] . "/css/master-style.css"), TRUE );

                $m_css = fopen(  $_SERVER['DOCUMENT_ROOT'] . "/css/master-style.css", "w");
                fwrite($m_css, $css);
                fclose($m_css);
                \Cache::forever('last_css_merge', $v);
        }
?>
<link rel="stylesheet" href="{{  asset('css/master-style.css'      )  }}{{  $v  }}">

Replace the list of files with the files you want merged into the master file (and change the path if not in /css/...).

You can also do this in pure PHP if you switch out the Laravel caching function with a pure PHP solution, which is relatively easy to do.

Download more RAM. 🐏 ⨉ 0 Posted by August R. Garcia 1 week ago

Edit History

• [2019-03-11 20:01 PDT] August R. Garcia (1 week ago)
🕓 Posted at 11 March, 2019 20:01 PM PDT

Profile Photo - August R. Garcia August R. Garcia Posting on Internet... Portland, OR
🗎 80 🗨 547 🐏 97
Site Owner

Grahew Mattham

August Garcia is some guy who used to sell Viagra on the Internet. He made this website to LARP as a sysadmin while posting about garbage like user-agent spoofing, spintax, the only good keyboard, virtual assitants from Pakistan, links with the rel="nofollow" attributeproxies, regular expressions, HTML and CSSsin, and probably some other trash.


Account created 3 months ago.
80 posts, 547 comments, and 97 RAMs.

Last active 16 hours ago:
Posted thread [19 March, 2019] 256 Kilobytes is the New Home of the Weekly Tuesday Night Maury Threads

Post a New Comment

To leave a comment, login to your account or create an account.

Do you like having a good time?

Read Quality Articles

Read some quality articles. If you can manage to not get banned for like five minutes, you can even post your own articles.

View Articles →

Argue with People on the Internet

Use your account to explain why people are wrong on the Internet forum.

View Forum →

Vandalize the Wiki

Or don't. I'm not your dad.

View Wiki →

Ask and/or Answer Questions

If someone asks a terrible question, post a LMGTFY link.

View Answers →

Make Some Money

Hire freelancers and/or advertise your goods and/or services. Hire people directly. We're not a middleman or your dad. Manage your own business transactions.

Register an Account
You can also login to an existing account or recover your password. All use of this site is subject to terms outlined in the terms of service and privacy policy.