Web Development Articles

Laravel Webpack.mix Asset Compilation AND Performance Optimization

0 👍
👎 0
 Laravel
 VueJS
 Javascript
 Blade

Getting Started with webpack.mix


This is an essential must know for Laravel developers.  This tutorial will go through the basics of webpack.mix and preparing live CSS stylesheets and Javascript includes.


Locate
webpack.mix.js and the /resources and /public directories.  I will define a few ways to specify the files from resources compiled to the live public directory.  Check out these 2 examples…  they should cover necessary usage for 99% of projects.

 

Example: Combine multiple files into a single file.

In this example I’ll define a simple way to combine multiple custom javascript files into a single file.  Let’s take 4 custom stylesheets and 4 javascript files.  We will combine all specified stylesheets from /resources/css into a single stylesheet named /public/css/custom-all.css.  Also let’s combine the specified javascript files from /resources/js into a single javascript file named /public/js/custom-all.js  


All files that can be edited directly are located in the resources directory.  All compiled files will be placed in the public directory where the code can be accessed live.

 

 mix.js('resources/js/app.js', 'public/js')

    .vue()

    .sass('resources/sass/app.scss', 'public/css');

 

 // Combine all custom JS into one file

 mix.scripts([

    'resources/js/custom/main.js',

    'resources/js/custom/helpers.js',

    'resources/js/custom/components/*.js'

 ], 'public/js/custom-all.js');

 

 // Combine all custom CSS into one file

 mix.styles([

    'resources/css/custom/main.css',

    'resources/css/custom/components/buttons.css',

    'resources/css/custom/pages/*.css'

 ], 'public/css/custom-all.css');

 

  

Let’s see how to use things in a blade template:

 

 <!DOCTYPE html>

 <html lang="en">

 <head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Your Laravel Application</title>

   

    <!-- Compiled CSS -->

    <link href="{{ mix('css/app.css') }}" rel="stylesheet">

    <link href="{{ mix('css/custom-all.css') }}" rel="stylesheet">

 </head>

 <body>

    <div id="app">

        <!-- Your application content -->

    </div>

 

    <!-- Compiled JavaScript -->

    <script src="{{ mix('js/app.js') }}"></script>

    <script src="{{ mix('js/custom-all.js') }}"></script>

 </body>

 </html>

 



Example: Prepare several files.


This example is very similar to the example above.  The only difference is in this example we are generating individual files in the
public directory for each file specified from the resources directory. 

 

 // Webpack-compiled JS and CSS

 mix.js('resources/js/app.js', 'public/js')

   .vue({ version: 2 })

   .sass('resources/sass/app.scss', 'public/css') // Or .css() if not using Sass

   .css('resources/css/app.css', 'public/css');

 

 // Custom JS files (separate from Webpack bundle)

 mix.js('resources/js/custom/main.js', 'public/js/custom.js')

   .js('resources/js/custom/helpers.js', 'public/js/helpers.js');

 

 // Custom CSS files (separate from Webpack bundle)

 mix.css('resources/css/custom/main.css', 'public/css/custom.css')

   .css('resources/css/custom/components/buttons.css', 'public/css/components/buttons.css');

 


Notice in
webpack.mix.js the definitions for mix.js and mix.css methods.  Each of the javascript files and stylesheets from the resources directory has a corresponding file in the public directory.

 

Now let’s look at how to use this in a blade template:

 

 <!DOCTYPE html>

 <html lang="en">

 <head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <title>Your Laravel Application</title>

   

    <!-- Compiled CSS -->

    <link href="{{ mix('css/app.css') }}" rel="stylesheet">

    <link href="{{ mix('css/custom.css') }}" rel="stylesheet">

    <link href="{{ mix('css/components/buttons.css') }}" rel="stylesheet">

 </head>

 <body>

    <div id="app">

        <!-- Your application content -->

    </div>

 

    <!-- Compiled JavaScript -->

    <script src="{{ mix('js/app.js') }}"></script>

    <script src="{{ mix('js/custom.js') }}"></script>

    <script src="{{ mix('js/helpers.js') }}"></script>

 </body>

 </html>

 

 

To generate the public CSS and JS files:

 

 npm install

 npm run dev

 

Master JavaScript Asynchronous Programming with Promise.allSettled()

0 👍
👎 0
 Javascript

The Promise.allSettled() method is a powerful tool for handling multiple promises in JavaScript. It returns a single Promise that resolves with an array of objects, each representing the outcome of a promise in the input array.

Each outcome object contains a status property, which is either 'fulfilled' or 'rejected'.

- If the status is 'fulfilled', the object will also contain a value property with the resolved value.

- If the status is 'rejected', the object will contain a reason property with the error (typically the value passed to reject).

Key Difference: Promise.allSettled() vs. Promise.all()

Unlike Promise.all(), which immediately rejects if any promise in the iterable is rejected, Promise.allSettled() never short-circuits. It waits for all promises to settle (either fulfill or reject), making it ideal for use cases where you need to know the result of every asynchronous operation, regardless of individual failures. This provides a more robust way for error handling in async/await and promise chains.

When to use Promise.allSettled() in JavaScript?
Use it whenever you need to process the results of multiple independent asynchronous operations and you don't want a single failure to prevent you from handling the others. Common scenarios include making multiple API calls or database queries where individual failures are non-critical.

The following example demonstrates how to use Promise.allSettled() to handle a mix of successful and failed promises.

 

 // Example: Handling multiple API calls or asynchronous tasks

 const p1 = new Promise((resolve, reject) => {

    setTimeout(resolve, 200, "Data for User 1"); // Simulates a successful API call

 });

 const p2 = new Promise((resolve, reject) => {

    setTimeout(resolve, 200, "Data for User 2"); // Simulates another successful call

 });

 const p3 = new Promise((resolve, reject) => {

    setTimeout(reject, 200, "User 3 not found"); // Simulates a failed API call (e.g., 404)

 });

 const p4 = new Promise((resolve, reject) => {

    setTimeout(reject, 200, "Server error for User 4"); // Simulates a server error (e.g., 500)

 });

 

 // Execute all promises and handle results with allSettled

 Promise.allSettled([p1, p2, p3, p4])

 .then(results => {

    console.log("All operations settled:");

    results.forEach((result, index) => {

       if (result.status === 'fulfilled') {

           console.log(`Promise ${index + 1}: Success -`, result.value);

       } else {

           console.log(`Promise ${index + 1}: Failed -`, result.reason);

       }

    });

 });

 

 //             ** CONSOLE OUTPUT **

 // All operations settled:

 // Promise 1: Success - Data for User 1

 // Promise 2: Success - Data for User 2

 // Promise 3: Failed - User 3 not found

 // Promise 4: Failed - Server error for User 4

 

 

JavaScript Asynchronous Programming with Promise any()

0 👍
👎 0
 Javascript

Promise.any() is a powerful JavaScript method introduced in ECMAScript 2021 that allows you to handle multiple promises simultaneously. This method returns a single promise that resolves as soon as any one of the input promises fulfills, making it ideal for scenarios where you want the fastest successful result.


Browser and Node.js Compatibility

Node.js: 15.0.0+ (native support)

Chrome: 85+

Firefox: 79+

Safari: 14+

 

For optimal compatibility and performance, we recommend using the latest Node.js LTS version.

 

How Promise.any() Works
Promise.any() takes an iterable of promises and returns a promise that:

 

- Resolves with the value of the first successfully fulfilled promise
- Rejects only if all input promises are rejected

 

Key Characteristics:

 

- Returns the first successful promise (not necessarily the fastest)

- Ignores rejected promises until all promises fail

- Perfect for fallback strategies and redundancy

 

Practical Examples


Example 1: First Successful Promise Wins

 

 // Create promises with different resolve/reject patterns

 const fastPromise = new Promise((resolve, reject) => {

    setTimeout(reject, 100, "fast: rejected");

 });

 

 const mediumPromise = new Promise((resolve, reject) => {

    setTimeout(reject, 99, "medium: rejected");

 });

 

 const slowPromise = new Promise((resolve, reject) => {

    setTimeout(resolve, 50, "slow: resolved");

 });

 

 const veryFastPromise = new Promise((resolve, reject) => {

    setTimeout(() => resolve('very fast: resolved'), 205);

 });

 

 // Use Promise.any() to get the first successful result

 Promise.any([slowPromise, mediumPromise, fastPromise, veryFastPromise])

   .then((result) => {

       console.log("First successful promise:", result);

       // Output: "slow: resolved"

   })

   .catch(error => {

       console.log("All promises failed");

   });

 

 

Example 2: Handling Complete Failure

 

 // All promises will be rejected

 const rejectedFast = new Promise((resolve, reject) => {

    setTimeout(reject, 100, "fast: rejected");

 });

 

 const rejectedMedium = new Promise((resolve, reject) => {

    setTimeout(reject, 99, "medium: rejected");

 });

 

 const rejectedSlow = new Promise((resolve, reject) => {

    setTimeout(reject, 50, "slow: rejected");

 });

 

 const rejectedVeryFast = new Promise((resolve, reject) => {

    setTimeout(() => reject('very fast: rejected'), 205);

 });

 

 Promise.any([rejectedSlow, rejectedMedium, rejectedFast, rejectedVeryFast])

   .then((result) => {

       console.log("Success:", result);

   })

   .catch(error => {

       console.log("Total failures:", error.errors.length);

      

       // Iterate through all rejection reasons

       error.errors.forEach((rejection, index) => {

           console.log(`Failure ${index + 1}:`, rejection);

       });

   });

 

 // Output:

 // Total failures: 4

 // Failure 1: slow: rejected

 // Failure 2: medium: rejected

 // Failure 3: fast: rejected

 // Failure 4: very fast: rejected

 

 

Error Handling Best Practices

Always include a .catch() block when using Promise.any(). Without proper error handling, you might encounter:

 
UnhandledPromiseRejection: This error originated either by throwing inside of

 an async function without a catch block, or by rejecting a promise which was

 not handled with .catch(). The promise rejected with the reason "slow promise

 Rejected".

 

Proper Error Handling Pattern:

 

 Promise.any([promise1, promise2, promise3])

 .then(result => {

    // Handle successful result

    console.log("Success:", result);

 })

 .catch(error => {

    // Handle case where all promises failed

    console.log("All promises rejected");

    console.log("Rejection reasons:", error.errors);

 })

 .finally(() => {

    // Cleanup code that runs regardless of outcome

    console.log("Operation completed");

 });

 

 

Real-World Use Cases

1. Multiple API Endpoints with Fallback

 

 const primaryAPI = fetch('https://primary-api.com/data');

 const backupAPI = fetch('https://backup-api.com/data');

 const cacheAPI = fetch('https://cache-api.com/data');

 

 Promise.any([primaryAPI, backupAPI, cacheAPI])

 .then(response => response.json())

 .then(data => {

    console.log("Data from fastest available source:", data);

 })

 .catch(() => {

    console.log("All data sources unavailable");

 });

 


2. Resource Loading with Redundancy

 

 const cdn1 = loadScript('https://cdn1.com/library.js');

 const cdn2 = loadScript('https://cdn2.com/library.js');

 const cdn3 = loadScript('https://cdn3.com/library.js');

 

 Promise.any([cdn1, cdn2, cdn3])

 .then(() => {

    console.log("Library loaded successfully");

    initializeApp();

 })

 .catch(() => {

    console.error("All CDNs failed - using local fallback");

    loadLocalFallback();

 });

 

 

 

PHP Access Modifiers (public, private, protected)

0 👍
👎 0
 PHP
 LAMP

In PHP Object-Oriented programming, public, private, and protected are access modifiers (visibility keywords) used to control how properties (variables) and methods (functions) of a class can be accessed.

They are important in Object-Oriented Programming (OOP) because they enforce encapsulation (controlling how data is exposed and used).


Public
Members declared public can be accessed from inside the class, outside of the class and by subclasses (child classes).  If no visibility is specified on a property the default will be public.


class
Car {

    public $brand;

    public function setBrand($brand) {

   $this->brand = $brand; // accessible inside the class

    }

 }

 $car = new Car();

 $car->brand = "Toyota"; // accessible outside the class

echo $car->brand; // Output: Toyota


Private

Members declared private can only be accessed inside of the class that defines them.  They cannot be accessed from outside the class or by subclasses.

 


class Car {

    private $engineNumber;

    public function setEngineNumber($num) {

       $this->engineNumber = $num; // accessible inside the class

    }

 

    public function getEngineNumber() {

       return $this->engineNumber; // allowed via public method

    }

 }

 

 $car = new Car();

 $car->setEngineNumber("ENG123");

 // echo $car->engineNumber; ERROR: Cannot access private property

 echo $car->getEngineNumber(); // Output: ENG123

 

 

Protected

Members declared protected can be accessed inside of the class, in child(sub) classes that inherit from it.  They cannot be accessed directly from outside of the class… only subclasses.

 

class Vehicle {

  protected $type = "Generic Vehicle";

 

   protected function getType() {

       return $this->type;

   }

}

 

class Car extends Vehicle {

  public function showType() {

       return $this->getType(); // accessible in child class

   }

}

 

$car = new Car();

// echo $car->type; ERROR: Cannot access protected property

echo $car->showType(); // Output: Generic Vehicle

 

 

PHP Match Expression (match)

0 👍
👎 0
 Laravel
 PHP

PHP Match Expression (match)


The PHP match expression is a powerful feature introduced in PHP 8.0 that provides a more concise and flexible alternative to switch statements.

 

Basic Match Syntax

 

$result = match ($value) {

  pattern1 => expression1,

  pattern2 => expression2,

  // ...

  default => default_expression,

};

 

 

Comparison switch vs match

 

// switch statement

switch ($statusCode) {

   case 200:

       $message = 'OK';

       break;

   case 404:

       $message = 'Not Found';

       break;

   case 500:

       $message = 'Server Error';

       break;

   default:

       $message = 'Unknown';

}

 

// match equivalent

$message = match ($statusCode) {

  200 => 'OK',

   404 => 'Not Found',

   500 => 'Server Error',

   default => 'Unknown',

};

 

 

Various Usage Examples:

 

 // multiple conditions

 $result = match ($httpCode) {

    200, 201, 202 => 'Success',

    400, 401, 403 => 'Client Error',

    500, 501, 502 => 'Server Error',

    default => 'Unknown',

 };

 

 // Match uses strict comparison (===)

 $result = match ($value) {

    0 => 'Integer zero',

    '0' => 'String zero',

    false => 'Boolean false',

    default => 'Other',

 };

 

 // Complex Expressions

 $age = 25;

 $category = match (true) {

    $age < 13 => 'Child',

    $age < 20 => 'Teenager',

    $age < 65 => 'Adult',

    default => 'Senior',

 };

 

 // returning different types

 function processValue($value) {

    return match ($value) {

        'int' => 42,

        'string' => 'Hello World',

        'array' => [1, 2, 3],

        'bool' => true,

        default => null,

    };

 }

 

 // Using with arrays

 $user = [

    'role' => 'admin',

    'status' => 'active'

 ];

 

 $permissions = match ($user['role']) {

    'admin' => ['read', 'write', 'delete'],

    'editor' => ['read', 'write'],

    'viewer' => ['read'],

    default => [],

 };

 

 // nested match expressions

 $result = match ($type) {

    'number' => match ($value) {

        $value > 0 => 'Positive',

        $value < 0 => 'Negative',

        default => 'Zero',

    },

    'string' => 'String type',

    default => 'Unknown type',

 };

 

 // Conditional Logic in Patterns

 $score = 85;

 $grade = match (true) {

    $score >= 90 => 'A',

    $score >= 80 => 'B',

    $score >= 70 => 'C',

    $score >= 60 => 'D',

    default => 'F',

 };

 



Advantages Over Switch

- Returns a value - Can be assigned directly to variables
- No fall-through - Prevents accidental bugs
- Strict comparisons - More predictable behavior
- More concise - Less boilerplate code
- Better error handling - Throws UnhandledMatchError for unhandled cases

Important Notes
- Match expressions must be exhaustive or include a default case
- Throws UnhandledMatchError if no pattern matches and no default is provided
- Each arm must be a single expression (use anonymous functions for complex logic)
- Patterns are evaluated in order, first match wins

The match expression is a significant improvement that makes conditional logic more readable, safer, and more expressive in modern PHP code.

 

JavaScript Self-Invoked Functions (IIFEs)

0 👍
👎 0
 NodeJS
 Javascript

What is a self-invoked function? (IIFE)

A self-invoked function, also called an Immediately Invoked Function Expression (IIFE) is a Javascript function expression that is invoked immediately after its declaration.  A self-invoked function can be a valuable tool for creating isolated scopes and managing variable privacy in javascript applications.

 

Key aspects of IIFEs:

 

- IIFEs execute immediately when defined

- Allows creation of private scopes without polluting global namespace

- Return values can be assigned to variables

- Parameters can be passed to IIFEs



Basic syntax:

 

 (function() {

    // code here

 })();

 

 // OR arrow functions (ES6+)

 (() => {

       // code here

 })();

 

 

 

Why are IIFEs Necessary?

Immediate Execution with Parameters

 

 // Immediately logs provided data

 (function(date, location) {

    console.log(`Date: ${date.toDateString()}`);

    console.log(`Location: ${location}`);

 })(new Date(), 'Seattle');

 

 // Immediately logs:

 // Date: Thu Oct 16 2025

 // Location: Seattle

 

 

Avoiding Global Namespace Pollution

 

 // if multiple scripts use the same variable names

 // they won't conflict

 (function() {

    const restaurant = "Dairy Queen";

    console.log(user); // "Dairy Queen"

 })();

 

 (function() {

    const restaurant = "Burger King";

    console.log(user); // "Burger King"

 })();

 

 

Data Privacy/Encapsulation

 

 // Problem: counter value is vulnerable.

 var counter = 0;

 function increment() {

    return ++counter;

 }

 

 // FIX: keeps variables private. counterModule isn't directly accessible

 const counterModule = (function() {

    let count = 0;

   

    return {

        increment: function() {

            return ++count;

        },

        decrement: function() {

            return --count;

        },

        getCount: function() {

            return count;

        }

    };

 })();

 

 counterModule.count = 100; // WONT WORK!!

 // count is not accessible directly

 

 console.log(counterModule.getCount()); // 0

 counterModule.increment();

 console.log(counterModule.getCount()); // 1

 // OUPTUT: 0 1

 

 

Module Pattern Implementation

 

 const User = (function() {

    let memory = 0;

   

    function add(a, b) {

        return a + b;

    }

   

    function store(value) {

        memory = value;

    }

   

    function recall() {

        return memory;

    }

   

    // Only expose public methods

    return {

        add: add,

        store: store,

        recall: recall

    };

 })();

 

 console.log(Calculator.add(5, 3)); // 8

 Calculator.store(10);

 console.log(Calculator.recall()); // 10

 // memory is private and inaccessible

 

 

How To Use PHP Late Static Binding

0 👍
👎 0
 Laravel
 PHP

self:: vs static:: in PHP is all about inheritance and late static binding. So what is late static binding. When building a child class there may be a static property that overrides that same static property on the parent. So when extending this class you will potentially need access to the property on both classes. The way to do this is through late static binding. You can use the self:: and static:: operators to accomplish this.

self::

 - Refers to the class where the method is defined.

 - Does not consider inheritance overrides.

static::

 - Refers to the class that is actually called at runtime.

 - This is called late static binding.

 - Allows child classes to override static properties/methods and still be respected.

Example: self:: vs static::

 

 class Animal {

    public static $type = "Generic Animal";

 

    public static function getTypeUsingSelf() {

        return self::$type// bound to Animal

    }

 

    public static function getTypeUsingStatic() {

        return static::$type; // late static binding

    }

 }

 

 class Dog extends Animal {

    public static $type = "Dog";

 }

 

 // ------------------- USAGE -------------------

 

 echo Dog::getTypeUsingSelf();   // Output: Generic Animal

 echo "<br>";

 echo Dog::getTypeUsingStatic(); // Output: Dog