256 Kilobytes

How to Automatically Merge and Minify CSS Files in Laravel 5.7

Articles in Frameworks | By August R. Garcia

Published | Last Update

This also basically works for PHP in general.

785 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.

// 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 . " ");

                // 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);
                \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. 🐏 ⨉ 0Posted by August R. Garcia 2 years ago

Edit History

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

Profile Photo - August R. GarciaAugust R. GarciaLARPing as a Sysadmi...Portland, ORSite Owner

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" attributeproxiessin, the developer console, literally every link building method, and other junk.

Available at arg@256kilobytes.com, via Twitter, or arg.256kilobytes.com. Open to business inquiries based on availability.

Post a New Comment

Do you like having a good time?

Register an Account

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

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