Web Development Articles

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)

 );

 




Using the Javascript Switch Statement

1 👍
👎 0
 NodeJS
 ReactJS
 Javascript

Overview of the Switch Statement


  The switch statement is a control structure available in almost every programming and scripting language.  It allows the developer to execute different blocks of code based on the value of an expression.  It is often used as a cleaner alternative to multiple if-else statements.  You may be asking yourself why use the switch statement since we already have if-else.  


   There are differences though.  And depending on the task-at-hand, the switch statement can be a better alternative than
if-else.  

Structure:

 

 switch (expression) {

    case value1:

        // execute this code block only

        break;

    case value2:

        // execute this code block only

        break;

    default:

        // execute if no cases match

 }


   A
switch statement evaluates an expression and executes the code block for the first case that matches its value.

   The break keyword is crucial. When encountered, it exits the entire switch statement immediately. Without it, execution will "fall through" and run the code in the subsequent case, even if the value doesn't match.  If no matching case is found, the optional default block is executed.

Example:

 

 let day = 'Monday';

 let output = '';

 switch (day) {

    case 'Monday':

        output = `Day is Monday`;

    case 'Tuesday':

        output = `Day is Tuesday`;

        break;

    case 'Wednesday':

        output = `Day is Wednesday`;

        break;

    case 'Thursday':

        output = `Day is Thursday`;

        break;

    case 'Friday':

        output = `Day is Friday`;

        break;

    case 'Saturday':

        output = `Day is Saturday`;

        break;

    case 'Sunday':

        output = `Day is Sunday`;

        break;

    default:

        output = `No day specified`;

 }

 

 // Output if day == 'Monday' OR day == 'Tuesday':

 // Day is Tuesday

 

 // Output if day == 'Saturday':

 // Day is Saturday

 

 // Output if day == 'Nothing'

 // No day specified

 


   This example demonstrates a crucial concept in JavaScript's
switch statement: fallthrough.  When day is 'Monday', the output will indeed be "Day is Tuesday".  Here’s why: The switch statement finds a match on case 'Monday' and begins executing the code on the next line, setting output = 'Day is Monday'.

  Because there is no break keyword at the end of the 'Monday' case, the logic "falls through" and continues to execute the very next line of code, which is the start of the 'Tuesday' case.  It then executes output = 'Day is Tuesday', overwriting the previous value.  Finally, the break keyword at the end of the 'Tuesday' case is encountered, which halts the execution of the switch block entirely.

   The break statement is not optional for most use cases. It is essential for exiting the switch block once a specific case's code has finished running. Without it, execution will continue into the next case, whether it matches or not.


   The
default case is only executed if no other case values match the expression. It will not be executed simply because of a fallthrough from a matched case (unless that fallthrough leads all the way to it).

self:: vs static:: in PHP

0 👍
👎 1
 PHP
 LAMP

self:: vs static:: in PHP is all about inheritance and late static binding.  It’s used when you are dealing with overrides and methods coming from the parent class.

 

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.

 

 class Automobile {

    public static $type = "Automobile";

 

    public static function getTypeUsingSelf() {

        return self::$type// bound to Automobile

    }

 

    public static function getTypeUsingStatic() {

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

    }

 }

 

 class Car extends Automobile {

    public static $type = "Car";

 }

 

 class Truck extends Automobile {

    public static $type = "Truck";

 }

 

 class Van extends Automobile {

    public static $type = "Van";

 }

 

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

 

 echo Car::getTypeUsingSelf();   // Output: Automobile

 echo "<br>";

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

 

 

PHP Object Oriented Class Inheritance

0 👍
👎 0
 PHP
 LAMP

PHP class inheritance is a mechanism that allows one class (called the child class or subclass) to inherit properties and methods from another class (called the parent class or superclass).

 

This allows you to reuse code, extend existing functionality, and follow the principle of "Don’t Repeat Yourself (DRY)".


Basics of Inheritance

1. The extends keyword is used in PHP to create inheritance.

2. A child class automatically inherits all the public and protected properties and methods of its parent class.

3. The child class can:

       A. Use the inherited methods and properties directly.

       B. Override methods from the parent class.

       C. Add new methods and properties.

 

Example 1: Basic Inheritance

Here, the Dog class inherits from the Animal class but overrides the speak() method.

 

 // Parent class

 class Animal {

    public $name;

 

    public function __construct($name) {

        $this->name = $name;

    }

 

    public function speak() {

        echo "$this->name makes a sound.<br>";

    }

 }

 

 // Child class

 class Dog extends Animal {

    public function speak() {

        echo "$this->name barks! Woof Woof!<br>";

    }

 }

 

 // Usage

 $animal = new Animal("Generic Animal");

 $animal->speak(); // Output: Generic Animal makes a sound.

 

 $dog = new Dog("Buddy");

 $dog->speak(); // Output: Buddy barks! Woof Woof!

 

 

Example 2: Using parent:: to Call Parent Methods

The Car class overrides the start() method but still uses the parent’s method with parent::start().

 

 class Vehicle {

    public function start() {

        echo "Starting the vehicle...<br>";

    }

 }

 

 class Car extends Vehicle {

    public function start() {

        // Call the parent method first

        parent::start();

        echo "Car engine started!<br>";

    }

 }

 

 $car = new Car();

 $car->start();

 // Output:

 // Starting the vehicle...

 // Car engine started!

 

 

Example 3: Multilevel Inheritance

Human inherits from Animal, and Animal inherits from LivingBeing. So, Human has all methods from both parents.

 

 class LivingBeing {

    public function breathe() {

        echo "Breathing...<br>";

    }

 }

 

 class Animal extends LivingBeing {

    public function eat() {

        echo "Eating...<br>";

    }

 }

 

 class Human extends Animal {

    public function speak() {

        echo "Speaking...<br>";

    }

 }

 

 $person = new Human();

 $person->breathe(); // From LivingBeing

 $person->eat();     // From Animal

 $person->speak();   // From Human

 

 

Javascript Spread Operator ...

0 👍
👎 0
 MongoDB

The javascript spread operator ... is a convenient way to insert an array into a second array.  Used mainly when defining the array data.  Consider the following:

/****
 * The x array is placed inside of noSpread as a child array inside.
 * noSpread array is now ['u', Array(2), 3, 7]
 ****/
let x = ['a', 2];
let noSpread = ['u', x, 3, 7];

/***
 * using the spread operator ...x
 * the spread array is now ['u', 'a', 2, 5, 6]
 ***/
 
let x = ['a', 2];
let spread = ['u', ...x, 5, 6];

 

PHP Object __invoke()

0 👍
👎 0
 PHP

What is the __invoke() method used for in objects?  The __invoke() method is a PHP magic method that allows an object to be called as if it were a function.  It’s great for maintaining state and focusing on a single calculation.

Let’s take a look a more practical use.  In this example we will use it for issuing API requests:

 

 class HttpRequest {

   

    public function __construct(private string $url)

    {   

    }

 

    public function __invoke($data) {

        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $this->url);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        $response = curl_exec($ch);

        curl_close($ch);

        return $response;

    }

 }

 

 $amazon = new HttpRequest('https://api.example.com/amazon/store');

 $temu = new HttpRequest('https://api.example.com/temu/store');

 

 $amazonResponse = $amazon(['item_id'=>12333]);

 $temuResponse = $amazon(['item_id'=>12333]);

 

 

JavaScript Variable Types (var, const, let)

0 👍
👎 0
 MySQL

There are 3 types of variables commonly used in javascript.  The main difference with the let type it's block scope.  If it's defined inside of a block it can't be accessed outside of the block.   Let's look at each in more detail:

const

Variables defined with const cannot be Redeclared
Variables defined with const cannot be Reassigned
Variables defined with const have Block Scope


// INCORRECT - must be assigned a value when it's declared.
const x;  
x = 1.999;

// INCORRECT - it cannot be reassigned a value
const x = 1.999;

x = 8;  

// IF defined inside of a block it has block scope. Look at example below:
if( somecondition )
{
   const x = 9;
}
// x cannot be access here outside of the "block", curly brackets.
// Below are valid usage of const:
// Example 1:
if( condition )
{
   const x = 8;
   console.log(x);
}

// Example 2:
const x = 8;
if( condition )
{
   console.log(x);
}