Laravel CDN Integration

The Laravel CDN integration could be done with either the CDN Assets Manager Package in combination with an AWS S3 bucket, the Simple CDN Package or by creating a helper that rewrites the URLs of your static assets. The following tutorial describes the creation of a helper in Laravel 5 to map your assets to the CDN URL.

  1. Create a pull zone before you start the Laravel CDN integration.
  2. Create the ./app/helpers.php file and update the ./composer.json as follow:
    ...
    "autoload": {
        "classmap": [
          ...
         ],
         ...
         "files": [
             "app/helpers.php"
         ]
    },
    ...
    
  3. Execute the command composer dump-autoload to dump the autoloader.
  4. Add the following code to your ./app/helpers.php:
    <?php
    
    // global CDN link helper function
    function cdn( $asset ){
    
        // Verify if KeyCDN URLs are present in the config file
        if( !Config::get('app.cdn') )
            return asset( $asset );
    
        // Get file name incl extension and CDN URLs
        $cdns = Config::get('app.cdn');
        $assetName = basename( $asset );
    
        // Remove query string
        $assetName = explode("?", $assetName);
        $assetName = $assetName[0];
    
        // Select the CDN URL based on the extension
        foreach( $cdns as $cdn => $types ) {
            if( preg_match('/^.*\.(' . $types . ')$/i', $assetName) )
                return cdnPath($cdn, $asset);
        }
    
        // In case of no match use the last in the array
        end($cdns);
        return cdnPath( key( $cdns ) , $asset);
    
    }
    
    function cdnPath($cdn, $asset) {
        return  "//" . rtrim($cdn, "/") . "/" . ltrim( $asset, "/");
    }
    ...
    

    The standard asset() function will be called if no CDN URLs are defined in the ./config/app.php config file.

  5. Define the CDN URLs in the ./config/app.php file.
    <?php
    
    return [
    
            /*
            |--------------------------------------------------------------------------
            | Application KeyCDN domains
            |--------------------------------------------------------------------------
            |
            | Specify different domains for your assets.
            |
            */
            'cdn' => array(
                    "cdn.keycdn.com" => "css|js|eot|woff|ttf",
                    "img.keycdn.com" => "jpg|jpeg|png|gif|svg",
                    "all.keycdn.com" => ""
            ),
    
            ...
    

    Example:
    KeyCDN Laravel CDN URLs

  6. Use the global helper function in your views:
    <img src="{{ cdn( "/img/yourImg.png" ) }}" alt="Your Image loaded from KeyCDN" />
  7. Verify the HTML source code if your assets are loading from KeyCDN.
    Laravel CDN verify source code

Leave A Comment?