Web Development Articles

Scoped Slot in Vue 2 (Options API)

0 👍
👎 0
 Laravel
 VueJS
 Javascript

With scoped slots, the child component can pass data to the slot content in the parent. That way, the parent can decide how to render data coming from the child.

 

1. Child Component (List.vue)

 

 <template>

   <ul>

     <!-- we expose each item to the slot -->

     <li v-for="(item, index) in items" :key="index">

       <!-- default slot gets props -->

       <slot :item="item" :index="index">

         <!-- fallback content if parent doesn't use scoped slot -->

         {{ index }} - {{ item }}

       </slot>

     </li>

   </ul>

 </template>

 

 <script>

  export default {

    name: "List",

    props: {

      items: {

        type: Array,

        required: true

      }

    }

  }

 </script>

 

 

2. Parent Component (App.vue)

 

 <template>

   <div>

     <h1>Scoped Slots Example</h1>

 

     <!-- Using scoped slot -->

     <List :items="categories">

       <template v-slot:default="slotProps">

         <!-- slotProps.item and slotProps.index come from child -->

         <strong>{{ slotProps.index + 1 }}.</strong> {{ slotProps.item.toUpperCase() }}

       </template>

     </List>

 

     <!-- Without scoped slot (fallback from List.vue will be used) -->

     <List :items="tags" />

   </div>

 </template>

 

 <script>

 import List from "./List.vue";

 export default {

    name: "App",

    components: { List },

    data() {

       return {

         categories: ["News", "Sports", "Entertainment"],

         tags: ["vue", "laravel", "slots"]

       };

    }

 }

 </script>

 

 

Javascript Null Coalescing Operator ??

0 👍
👎 0
 NodeJS

The double question mark ?? in javascript is referred to as the null coalescing operator.  It was introduced in JavaScript ES2020.  It allows you to check for null or undefined variable.   In most cases the order of operation for this operator follows the math and comparison operators.  Below are a few examples: 


Example 1:
let myval = null;
console.log(myval ?? 20); // output is 20 because myval is null

Example 2:
console.log(myval ?? 20); // output is 20 because myval is undefined

Example 3:
let myval = [];
console.log(myval ?? [1,2,3]);  // output is [] because it isn't null and it's not undefined

If the myval is anything other than null or undefined, the output will be the value of the right-hand side of the equation.

 

Javascript Map, Filter, Reduce methods

0 👍
👎 0
 MongoDB

Map

The map() method is used for creating a new array from an existing one, applying a function to each one of the elements of the first array.

let numbers = [1, 2, 3, 4, 5];
let doubled = numbers.map(num => num * 2);
console.log(doubled) // [2, 4, 6, 8, 5] 

Filter

The filter() method takes each element in an array and it applies a conditional statement against it. If this conditional returns true, the element gets pushed to the output array. If the condition returns false, the element does not get pushed to the output array.

const numbers = [1, 2, 3, 4];
const odds = numbers.filter(num => num % 2 === 1);
console.log(odds); // [1, 3]

Or with an array of Objects you can implement filter() like the following.  

const students = [
{name: 'eric', age: 12},
{name: 'Jenny' age: 11},
{name: 'Freddy', age: 9}
];
const overTen = students.filter(student => student.age > 10); console.log(overTen); // [{name:'Eric', age:12}, {name:'Jenny', age:11}]

Reduce

The reduce() method reduces/calculates a value down to a single value. To get the output value, it runs a reducer function on each element of the array.

const array1 = [1, 2, 3, 4];   // 0 + 1 + 2 + 3 + 4
const initialValue = 10;
const sumWithInitial = array1.reduce(
(accumulator, currentValue) => accumulator + (currentValue * 10), 
initialValue
);

// Expected output is 110.  Ok so the accumulator starts at the value of zero.  And then accumulator is accumulator plus currentValue times 10.  Add 10(initialValue... we set it to 10) + 10 + 20 + 30 + 40

 

What is the PHP Spread Operator (...)

0 👍
👎 0
 PHP

Spread Operator (...)

The PHP Spread Operator (...) is a powerful feature introduced in PHP 5.6 that allows you to "unpack" or "spread" elements from arrays and traversable objects. It's also known as the splat operator or unpacking operator.

The spread operator is particularly useful in modern PHP development for creating more expressive and efficient code when working with arrays and variable function arguments.

Key Benefits of the PHP Spread Operator

  1. Cleaner syntax for array merging and function calls

  2. Better performance in some cases compared to array_merge()

  3. More readable code when dealing with multiple arrays

  4. Flexible for both array operations and function arguments


Here are a few common use cases for the operator:

Unpack and Merge Multiple Arrays

Here are a couple of examples for unpacking and merging arrays.  

 

 $array1 = [1, 2, 3];

 $array2 = [4, 5, 6];

 $array3 = [7, 8, 9];

 

 $merged = [...$array1, ...$array2, ...$array3];

 

 // Array (

 //  [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5

 //  [5] => 6 [6] => 7 [7] => 8 [8] => 9

 // )

 

 

 $original = ['b', 'c', 'd'];

 $newArray = ['a', ...$original, 'e'];

 // Array (

 //   [0] => a [1] => b [2] => c [3] => d [4] => e

 // )

 

 

Function Arguments

 

 // FUNCTION ARGUMENTS

 function addNumbers($a, $b, $c) {

    return $a + $b + $c;

 }

 

 $numbers = [2, 4, 6];

 $result = addNumbers(...$numbers);

 echo $result; // Output: 12

 

 

 function sum(...$numbers) {

    return array_sum($numbers);

 }

 

 $values = [1, 2, 3, 4, 5];

 echo sum(...$values); // Output: 15

 

Combining With Regular Elements

 

 // Combining with Regular Elements

 $first = [1, 2];

 $last = [5, 6];

 $combined = [...$first, 3, 4, ...$last];

 print_r($combined);

 // Output: Array ([0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6)

 

 

Usage With Associative Arrays

Notice that array keys are also considered making it perfect for merging associative arrays as well.  

 //With Associative Arrays

 $config1 = ['host' => 'localhost', 'port' => 3306];

 $config2 = ['username' => 'root', 'password' => 'secret'];

 

 $finalConfig = [...$config1, ...$config2];

 print_r($finalConfig);

// Output: Array ([host] => localhost [port] => 3306 [username] => root [password] => secret)

 

 

String To Array Conversion

 

 // String To Array Conversion

 $string = "hello";

 $chars = [...$string];

 print_r($chars);

 // Output: Array ([0] => h [1] => e [2] => l [3] => l [4] => o)

 

 

Practical Example of Merging 2 Configuration Arrays

Remember that when merging 2 associative arrays using the spread operator and brackets syntax, the second array in the will overwrite values with matching keys.  Take a look at the ‘debug’ key below:

 

 // Configuration Merging

 $defaultConfig = [

    'debug' => false,

    'cache' => true,

    'timeout' => 30

 ];

 

 $userConfig = [

    'debug' => true,

    'database' => 'mysql'

 ];

 

 $finalConfig = [...$defaultConfig, ...$userConfig];

 print_r($finalConfig);

 // Output: Array ([debug] => true [cache] => true [timeout] => 30 [database] => mysql)

 




PHP Null Coalescing Assignment (??=)

0 👍
👎 0
 PHP

PHP Null-Coalescing Assignment (??=)

The PHP Null-Coalescing Assignment operator ??= is a shorthand that combines the null coalescing operator ?? with an assignment = operator.


Some benefits of the null coalescing assignment operator is it reduces code verbosity significantly. It’s readable with clear intent for setting defaults. It’s safe and avoids undefined variable notices. It’s efficient with a single operation instead of multiple lines.

Below is 3 different ways of accomplishing the same objective. The value of $variable will be 30. The first example uses the ??= (null-coalescing assignment) operator. Notice it's a shorthand for the other 2 similar methods:

 

 // Null-Coalescing Assignment (all-in-one)

 $variable ??= 30;

 

 // Null Coalescing combined with Assignment

 $variable = $variable ?? 30;

 

 // Ternary Operator combined with Assignment

 $variable = $variable ? $variable : 30;


Here are a few different ways of using the Null-Coalescing Assignment operator
??=

 

 // Variable is null

 $name = null;

 $name ??= 'Peter';

 echo $name; // Output: 'Peter'

 

 // Variable already has a value

 $count = 25;

 $count ??= 30;

 echo $count; // Output: 25 (unchanged)

 

 // Variable doesn't exist

 $location ??= 'Chicago';

 echo $location; // Output: 'Chicago'

 

 

PHP Null Coalescing Operator ??

0 👍
👎 0
 LAMP
The null coalescing operator ?? is used similar to the elvis operator ?:  In the example below the value of $var3 will only be the value of $var2 if $var1 is null.  With no value will $var3 be the value of $var1. 
 
Example 1:

$var1 = null;  // it's null
$var2 = 15;
$var3 = $var1 ?? $var2; // the value is 15

OR
$var1;  // it's undfefined
$var2 = 15;
$var3 = $var1 ?? $var2; // the value is 15

In Example 1 above the value of $var3 will be the value of $var2.  This is because value of $var1 is null or undefined.  If $var1 is any value besides null, the value of $var3 would be the value of $var1.  That case is displayed in Example 2 below.

In Example 2:

$var1 = 3;
$var2 = 15;
$var3 = $var1 ?? $var2;   // the value is 3

Laravel Eloquent ORM Polymorphism Examples

0 👍
👎 0
 Laravel
 PHP
 PostgreSQL
 MySQL

Laravel Eloquent ORM Polymorphism

In Laravel's Eloquent ORM, polymorphism refers to polymorphic relationships, which allow a model to belong to more than one type of model using a single association.

This is useful when you have a relationship that can apply to multiple different models without having to create separate foreign keys or pivot tables for each type. Examples would be Users and Products that each have one or more images.

Let’s take a look at different types of polymorphic relationships commonly used in Laravel Eloquent ORM.

 

One-to-One (Polymorphic)

Example: An Image model could belong to either a User or a Product.

 
// Image model

public function imageable()

 {

    return $this->morphTo();

 }

 

 // User model

public function image()

 {

    return $this->morphOne(Image::class, 'imageable');

 }

 

 // Product model

public function image()

 {

    return $this->morphOne(Image::class, 'imageable');

 }

 

Table Definitions: User, Product models can both have an Image.  Notice Image.imageable_id and Image.imageable_type.  This can join on both User.id and Product.id tables.

 

CREATE TABLE users (

   id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,

    name VARCHAR(255),

   email VARCHAR(255) UNIQUE

 );

 

CREATE TABLE products (

   id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,

    name VARCHAR(255),

   price DECIMAL(10,2)

 );

 

CREATE TABLE images (

   id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,

    url VARCHAR(255),

   imageable_id BIGINT UNSIGNED,  -- FK ID (user.id or product.id)

   imageable_type VARCHAR(255),   -- Model class (App\Models\User/App\Models\Product)

    INDEX idx_imageable (imageable_id, imageable_type)

 );

 




One-to-Many (Polymorphic)

Example: A Comment model could belong to both a Post and a Video.

 

 // Comment model

public function commentable()

 {

    return $this->morphTo();

 }

 

 // Post model

public function comments()

 {

    return $this->morphMany(Comment::class, 'commentable');

 }

 

 // Video model

public function comments()

 {

    return $this->morphMany(Comment::class, 'commentable');

 }

 

 

Table Definitions: Post, Video models can both have a Comment.  Notice Comment.commentable_id and Comment.commentable_type.  This can join on both Post.id and Video.id tables.

 

CREATE TABLE posts (

    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,

   title VARCHAR(255),

   body TEXT

 );

 

CREATE TABLE videos (

    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,

    title VARCHAR(255),

    url VARCHAR(255)

 );

 

CREATE TABLE comments (

    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,

    body TEXT,

    commentable_id BIGINT UNSIGNED, -- FK ID (post.id|video.id)

    commentable_type VARCHAR(255), -- Model class (App\Models\Post|App\Models\Video)

    INDEX idx_commentable (commentable_id, commentable_type)

 );

 



Many-to-Many (Polymorphic)

Example: A Tag model can be applied to both Post and Video.

 

 // Tag model

public function posts()

 {

    return $this->morphedByMany(Post::class, 'taggable');

 }

 

public function videos()

 {

    return $this->morphedByMany(Video::class, 'taggable');

 }

 

 // Post model

public function tags()

 {

    return $this->morphToMany(Tag::class, 'taggable');

 }

 

 // Video model

public function tags()

 {

    return $this->morphToMany(Tag::class, 'taggable');

 }

 



Table Definitions: Both Post, Video models can have multiple Tags.  Also, a Tag can belong to multiple Post, Video models.  Notice the pivot table taggables…   

 

CREATE TABLE tags (

    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,

    name VARCHAR(255) UNIQUE

 );

 

CREATE TABLE posts (

    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,

    title VARCHAR(255),

    body TEXT

 );

 

CREATE TABLE videos (

    id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,

    title VARCHAR(255),

    url VARCHAR(255)

 );

 

CREATE TABLE taggables (

    tag_id BIGINT UNSIGNED,    -- FK to tags.id

    taggable_id BIGINT UNSIGNED, -- FK ID (post.id or video.id)

    taggable_type VARCHAR(255), -- Model class (App\Models\Post / App\Models\Video)

    PRIMARY KEY (tag_id, taggable_id, taggable_type),

    INDEX idx_taggable (taggable_id, taggable_type)

 );