How to Generate Unique IDs for Chat Messages in Laravel with GridDB?

I’m building a real-time chat application using Laravel and want to use GridDB as my database due to its high performance with time-series data. Since GridDB doesn’t have an official PHP client, I’ve set up a custom integration using a middleware API in Python that communicates with GridDB. My Laravel application interacts with this middleware via HTTP requests.

In my chat application, each message needs a unique ID. In traditional relational databases like MySQL, I would use an auto-incrementing integer as the primary key. Since GridDB doesn’t support auto-incrementing IDs natively, I need a reliable way to generate unique IDs for chat messages that can handle high concurrency since multiple users might send messages simultaneously.

I tried combining the current timestamp with a random number:

$messageId = time() . mt_rand(1000, 9999);

This reduces the chance of collisions but isn’t foolproof, especially under high load.

I attempted to simulate auto-increment by querying the maximum existing ID and incrementing it:

$maxId = $this->getMaxMessageIdFromGridDB();
$messageId = $maxId + 1;

However, this approach isn’t safe in a concurrent environment and can lead to race conditions.

Would using GridDB’s TIMESTAMP row key with sub-second precision be a viable option for unique IDs?

Laravel Eloquent Query Running So SLOWLY as compared to mySQL counterpart

Why is this laravel eloquent query running so SLOWLY?

I have a query running in a Laravel job that executes very slowly and inconsistently. Sometimes it takes 1-2 minutes to fetch the result, while at other times it completes in just 1-2 seconds for the same exact query.

Slow Full Eloquent Query ( Takes 1-2 minutes for the query to be completed )

$relevantRobot = AppRobot::where('serial_number', 'TEST-ID')
                    ->whereHas('robot_maps', function($query) use ($robot_map_name) {
                        $query->where('name', $robot_map_name);
                    })
                    ->with(['robot_maps' => function($query) use ($robot_map_name) {
                            $query->where('name', $robot_map_name);
                        },
                        'current_robot_position',
                        'current_robot_position.robot_map',
                        'latest_robot_deployment_information_request'
                    ])
                    ->first(); // Get the raw SQL query

Slow Reduced Eloquent Query ( Takes 1-2 minutes for the query to be completed )

$relevantRobot = AppRobot::where('serial_number', 'TEST-ID')
                    ->whereHas('robot_maps', function($query) use ($robot_map_name) {
                        $query->where('name', $robot_map_name);
                    })
                    ->with(
                        'current_robot_position',
                    ])
                    ->first(); // Get the raw SQL query

Fast Reduced Eloquent Query ( Completes in less than a second )

$relevantRobot = AppRobot::where('serial_number', 'TEST-ID')
                    ->whereHas('robot_maps', function($query) use ($robot_map_name) {
                        $query->where('name', $robot_map_name);
                    })
                    ->with(
                        'latest_robot_deployment_information_request',
                    ])
                    ->first(); // Get the raw SQL query

SQL Query ( Completes in less than a second )

select * from `robots` where `serial_number` = 'TEST-ID' and exists (select * from `robot_maps` where `robots`.`id` = `robot_maps`.`robot_id` and `name` = 'test' and `active` = 1);

Eloquent Relationship

 public function current_robot_position(){
        return $this->hasOne('AppRobotMapPositionLog','robot_id','id')
            ->orderBy('id','desc');
    }

Attempted Solution

After noticing the slow load time when eagerly loading current_robot_position, I added indexes to the columns used in that relationship (id). However, this hasn’t improved the performance.

I also tried converting the Eloquent query to a raw MySQL query using toSql(), and it ran extremely fast (under 1 second).

What is wrong? What am I missing?

Trying to delete row from database with JS and PHP not working [duplicate]

I got this main PHP file (index.php), its has an html button with an int value and onclick it calls a JS function on the same file.

The JS function receives the value of the button and should send a POST request to another PHP file with the button’s value.

Then the PHP should execute another function.

Finally it comes back to the first html/JS file. I don’t know if it isn’t sending the request or what.

Button (index.php):
<input name="delete" class="imageButton" id="deleteButton" type="submit" value="<?php echo "{$id}";?>" onclick="pr()">

JS Function (index.php):

function pr() {
  if (confirm("¿Borrar contacto con id: " + document.getElementById("deleteButton").value  + "?")) {
    jQuery.ajax({
      url: "./Utils/DeleteContact.php",
      type: "POST",
      data: {"deleteContact": document.getElementById("deleteButton").value}
    });
    window.location.href = "./Utils/DeleteContact.php";
  }
}

DeleteContact.php:

<?php
    //TODO
    if (isset($_POST["deleteContact"])) {
        deleteContact($_POST["deleteContact"]);
        header("../index.php");
    }

    function deleteContact(int $id) {
        $delete = "delete from registros where id = {$id}";

        try {
            mysqli_query($_SESSION["connection"], $delete);
        } catch (mysqli_sql_exception) {
            echo '<p style="color: red;">Error al borrar contacto</p>';
        }
    }
?>

don’t know much of JS yet, tried using JQuery.post, get, ajax, using a variable for the ajax data and replacint JQuery. for $.

How to Integrate GridDB with Laravel Using a Custom Database Driver?

I’m working on a Laravel project where I want to use GridDB as my database. Since Laravel doesn’t have built-in support for GridDB, I’m trying to create a custom database driver to handle the connection, since there’s a connector for PHP in their docs. Here’s what I’ve done so far:

  1. Created a custom database driver:

'connections' => [ // Other connections...

'griddb' => [
'driver' => 'griddb',
'host' => env('GRIDDB_HOST', '127.0.0.1'),
'port' => env('GRIDDB_PORT', 10001),
'cluster' => env('GRIDDB_CLUSTER', 'myCluster'),
'username' => env('GRIDDB_USERNAME', 'admin'),
'password' => env('GRIDDB_PASSWORD', 'admin'),
],
],
  1. Created a service provider for it:
class GridDBServiceProvider extends ServiceProvider
{
public function register()
{
$this->app['db']->extend('griddb', function ($config, $name) {
$config['name'] = $name;
return new GridDBConnection($config);
});
}
}
  1. Added the Connection class:
class GridDBConnection extends Connection
{
protected $gridstore;



public function __construct(array $config)
{
$factory = StoreFactory::getInstance();
$this->gridstore = $factory->getStore([
'notificationMember' => $config['host'] . ':' . $config['port'],
'clusterName' => $config['cluster'],
'user' => $config['username'],
'password' => $config['password'],
]);



parent::__construct($this->gridstore);
}
}

  1. Added the service provider:
'providers' => [
// providers ..
AppProvidersGridDBServiceProvider::class,
]

So when I try to run migrations I get

unsupported driver [griddb].

Does anyone know what is happening, why is the connector not connecting?

Why use a different server to execute a force download script? [closed]

I m working on a project which uses an API to fetch URL of a video or audio, I want users to able to download the video/audio and for that I wrote script to force download the file. Everything is working correctly, but I recently discovered that other similar tools/apps uses a different host/domain to run the force download script.
for example, if their website is

www.abc.com

, the download link will be something like

dl.something.com/download?token=

the problem is I do not know how to achieve this corretly, if my website is

www.123.com

, force downloading script can be executed by

www.123.com/download?token=

so my questions are –

  1. Why others are using different server to host force download script ?
  2. What will be the correct way to achieve this, without using database, how session variables can be passed to a different host ?
  3. does it affect bandwidth ?

Apologies if I did not clarify everything correctly or if the questions are not correct, but m a beginner and couldn’t find answer to this anywhere

Fatal error: apply_filters() conflict in email Customizer plugin

I use a plugin Woocommerce Email Customizer but recently the email refused to work giving PHP Error email cannot display

  1. ***/public_html/wp-content/plugins/woocommerce-email-control/ec-email-control.php(1059): apply_filters()

  2. ***/public_html/wp-content/plugins/woocommerce-email-control/ec-email-control.php(1005): WC_Email_Control->ec_style_inline_for_old_wc()

  3. ***/public_html/wp-content/plugins/woocommerce-email-control/pages/ec-preview-page.php(195): apply_filters()

  4. **/public_html/wp-content/plugins/woocommerce-email-control/ec-email-control.php(562): require_once(‘//*/…’)

How do I tackle this and what does this error mean

There’s no more support for this plugin or update as developer is gone!

I have tried to rewrite the hook function but it just seems I’m not getting it

Twillo Object Printing difference between localhost and live server

require_once 'vendor/autoload.php';
use TwilioRestClient;

$sid    = "ACe39b1abc88826a6a4b571e0d0c829d25";
$token  = "579fd6e6fdb99ccdbd4db57d54e23ad6";
$twilio = new Client($sid, $token);

$verification_check = $twilio->verify->v2->services("VA60737f4811c8c00f6a9a5297962c2b3f")
                                   ->verificationChecks
                                   ->create([
                                                "to" => "+911234567890",
                                                "code" => "888577"
                                            ]
                                    );
print($verification_check);
print($verification_check->status);

the same code prints the whole object on localhost but prints [Twilio.Verify.V2.VerificationCheckInstance] like this on live worpress server . but I can access the properties like print($verification_check->status); on both local and live . Another point to mention I downloaded the twillo from composer on localhost and uploaded the directory to wordpress theme folder

Jazz Cash – API intergration ERROR – “Provided Transaction Type and Version are not allowed”

JazzCash Payment Integration Error: Transaction Type and Version Not Allowed

Problem

I’m trying to integrate JazzCash payment gateway in PHP but getting an error response saying “Provided Transaction Type and Version are not allowed”. I’m using their sandbox environment for testing.

Code

Here’s my PHP class for JazzCash integration:

class JazzCashPayment {
    private $merchantId;
    private $password;
    private $integritySalt;
    private $apiUrl;

    public function __construct($merchantId, $password, $integritySalt, $isProduction = false) {
        $this->merchantId = $merchantId;
        $this->password = $password;
        $this->integritySalt = $integritySalt;
        $this->apiUrl = $isProduction
            ? 'https://payments.jazzcash.com.pk/ApplicationAPI/API/2.0/Purchase/DoMWalletTransaction'
            : 'https://sandbox.jazzcash.com.pk/ApplicationAPI/API/2.0/Purchase/DoMWalletTransaction';
    }

    public function initializePayment($amount, $mobileNumber, $cnic) {
        date_default_timezone_set('Asia/Karachi');

        $DateTime = new DateTime();
        $dateTime = $DateTime->format('YmdHis');
        //------------------------------------------------------

        //------------------------------------------------------
        //expiry date, add 1 hour to $DateTime
        $ExpiryDateTime = $DateTime;
        $ExpiryDateTime->modify('+' . 1 . ' day');
        $expiryDateTime = $ExpiryDateTime->format('YmdHis');
        //------------------------------------------------------

        $txnRefNo = 'Sol' . $dateTime;
        // $amount = 100 * $amount;
        // Create data array with exact structure and order
        $data = array(
            "pp_CNIC" => $cnic,
            "pp_MobileNumber" => $mobileNumber,
            "pp_Language" => "EN",
            "pp_MerchantID" => $this->merchantId,
            "pp_Password" => $this->password,
            "pp_BankID" => "",
            "pp_ProductID" => "",
            "pp_TxnRefNo" => $txnRefNo,
            "pp_Amount" => $amount,
            "pp_TxnCurrency" => "PKR",
            "pp_TxnDateTime" => $dateTime,
            "pp_BillReference" => "billRef3781",
            "pp_Description" => "Test case description",
            "pp_TxnExpiryDateTime" => $expiryDateTime,  // Can be modified for different expiry
            "pp_SecureHash" => "",
            "ppmpf_1" => $mobileNumber,
            "ppmpf_2" => "",
            "ppmpf_3" => "",
            "ppmpf_4" => "",
            "ppmpf_5" => ""
        );

        // Generate and add secure hash
        $data['pp_SecureHash'] = $this->generateSecureHash($data);

        echo '<pre>';
        print_r($data);
        echo '</pre>';
        return $this->makeApiRequest($data);
    }

    public function generateSecureHash($data) {
        // Step 1: Collect only pp-prefixed fields, excluding pp_SecureHash, pp_TxnType, and pp_Version
        $ppData = [];
        foreach ($data as $key => $value) {
            $lowerKey = strtolower($key);
            if (strpos($lowerKey, 'pp') === 0 && $lowerKey !== 'pp_securehash' && $lowerKey !== 'pp_txntype' && $lowerKey !== 'pp_version') {
                $ppData[$lowerKey] = $value;
            }
        }

        // Step 2: Sort fields by ASCII alphabetical order of keys
        ksort($ppData);

        // Step 3: Build the hash string by concatenating values with `&` separator
        $hashString = '';
        foreach ($ppData as $key => $value) {
            if ($value !== "") {  // Only non-empty values
                $hashString .= ($hashString ? '&' : '') . $value;
            }
        }

        // Step 4: Prepend Integrity Salt
        $finalHashString = $this->integritySalt . '&' . $hashString;

        // Step 5: Generate the HMAC hash with SHA-256
        return strtoupper(hash_hmac('sha256', $finalHashString, $this->integritySalt));
    }

    /**
     * Debug method to verify hash generation
     */
    public function debugHash($data) {
        echo "Input Data:n";
        print_r($data);

        // Remove pp_SecureHash
        $ppData = $data;
        unset($ppData['pp_SecureHash']);

        // Sort by keys
        ksort($ppData);

        echo "nSorted Data:n";
        print_r($ppData);

        // Create hash string
        $str = '';
        foreach ($ppData as $value) {
            if ($value !== "") {
                $str = $str . '&' . $value;
            }
        }

        // Add integrity salt
        $str = $this->integritySalt . $str;

        echo "nHash String:n$strn";

        // Generate hash
        $hash = strtoupper(hash_hmac('sha256', $str, $this->integritySalt));
        echo "nGenerated Hash:n$hashn";

        return $hash;
    }

    private function makeApiRequest($data) {
        $curl = curl_init();

        curl_setopt_array($curl, [
            CURLOPT_URL => $this->apiUrl,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => json_encode($data),
            CURLOPT_HTTPHEADER => [
                'Content-Type: application/json',
                'Accept: application/json'
            ],
        ]);

        $response = curl_exec($curl);
        $err = curl_error($curl);

        curl_close($curl);

        if ($err) {
            throw new Exception("cURL Error: " . $err);
        }

        return json_decode($response, true);
    }
}

Usage

$jazzcash = new JazzCashPayment(
'XXXX',          // Merchant ID
'XXXXX',       // Password
'XXXX',    // Integrity Salt
false               // Use sandbox environment
);

$response = $jazzcash->initializePayment(
'100',           // Amount
'03123456789',   // Mobile Number
'345678'         // CNIC
);

Error Response

Array(
[pp_ResponseCode] => 110
[pp_ResponseMessage] => Provided Transaction Type and Version are not allowed.
// ... other response fields
)

What I’ve Tried

  • Verified all required fields are being sent
  • Double-checked the secure hash generation
  • Confirmed the API endpoint URL is correct
  • Verified merchant credentials

Question

Looking at the error message, it seems I’m missing the transaction type and version in the request. However, I couldn’t find clear documentation about how to include these parameters. Has anyone successfully integrated JazzCash payments who can point out what I’m missing?

Expected Behavior

The payment should be initialized successfully with the provided parameters.

Additional Context

  • Using PHP 7.4+
  • Testing in sandbox environment
  • Following JazzCash API v2.0`

Database connection with laravel application hosted on hostinger server sub domain [duplicate]

i have Hostinger server when i upload any laravel application on it and connect it with correct database credentials in env it shows
SQLSTATE[HY000] [1045] Access denied for user ‘u334339390_POLydooRdBUsr’@’127.0.0.1’ (using password: YES) (SQL: select * from sessions where id = 26DRGziVVIM0Z9Nn8F0tK8S3sd0FmrrEipRXwOSK limit 1)
but when i connect it with other existing database of existing other laravel application it connect successfully why for new it shows this
please give me its reasons and possible solutions

Document ID is not capturing in form using dropzone library

I am using form and dropzone library to upload document and I was doing testing whether my document ID is capturing or not. Its not capturing and when I check and see the issue is my form dropzone library is preventing it and I am not sure why. I will appreciate any help to identify the issue

This is my code

var tblCandidateDocumentList = $('#tblCandidateDocumentList').DataTable({
        ajax: {
            "url": "action/fn_espdb_getData.php?mod=candidateDocumentList",
            "dataSrc": "candidateDocumentList"
        },
        columns: [
            { data: null },
            {data: null},
            { data: 'document_type_name' },
            {
              data: null,
                render: function (data, type, row) {
                    return `
                      <div class="col-12">
                        <div class="card">
                          <div class="card-body">
                            <form action="/upload" class="dropzone dropZoneCandidate needsclick" data-doc-id="${row.document_id}" id="dropzone-multi-${row.document_id}">
                              <input type="hidden" id="documentTypeID" name="documentTypeID" value="${row.document_id}" class="form-control" readonly>
                              <div class="dz-message needsclick">
                                Drop files here or click to upload
                              </div>
                              <div class="fallback">
                               <input id="file_${row.document_id}" name="file_${row.document_id}" type="file" multiple/>
                              </div>
                            </form>
                          </div>
                        </div>
                      </div> 
                  `;
                }
            },
        ],
        columnDefs: [
          {
            // For Checkboxes
            targets: 0,
            searchable: false,
            orderable: false,
            render: function () {
              return '<input type="checkbox" class="dt-checkboxes form-check-input">';
            },
            checkboxes: {
              selectRow: true,
              selectAllRender: '<input type="checkbox" class="form-check-input">'
            }
          },
        ],
        order: [[1, 'desc']],
        dom: '<"row"<"col-sm-12 col-md-6"l><"col-sm-12 col-md-6 d-flex justify-content-center justify-content-md-end mt-n6 mt-md-0"f>><"table-responsive"t><"row"<"col-sm-12 col-md-6"i><"col-sm-12 col-md-6"p>>',
        language: {
            paginate: {
                next: '<i class="bx bx-chevron-right bx-18px"></i>',
                previous: '<i class="bx bx-chevron-left bx-18px"></i>'
            }
        },
        select: {
            style: 'multi'
        }
    });

This is my backend code

case “addCandidateDetails”:

    // Collect form data
    $candidateID = $_POST['candidateID'] > 0 ? $_POST['candidateID'] : NULL;
    $candidateName = $_POST['candidateName'] == "" ? NULL : $_POST['candidateName'];
    $candidateNationality = $_POST['candidateNationality'] == "" ? NULL : $_POST['candidateNationality'];
    $candidateGender = $_POST['candidateGender'] == "" ? NULL : $_POST['candidateGender'];
    $candidateMaritalStatus = $_POST['candidateMaritalStatus'] == "" ? NULL : $_POST['candidateMaritalStatus'];
    $candidateDOB = $_POST['candidateDOB'] == "" ? NULL : $_POST['candidateDOB'];
    $candidateAge = $_POST['candidateAge'] == "" ? NULL : $_POST['candidateAge'];
    $candidateEmail = $_POST['candidateEmail'] == "" ? NULL : $_POST['candidateEmail'];
    $candidateCompany = $_POST['candidateCompany'] == "" ? NULL : $_POST['candidateCompany'];
    $candidatePassportNo = $_POST['candidatePassportNo'] == "" ? NULL : $_POST['candidatePassportNo'];
    $candidatePassportIssueDate = $_POST['candidatePassportIssueDate'] == "" ? NULL : $_POST['candidatePassportIssueDate'];
    $candidatePassportExpiryDate = $_POST['candidatePassportExpiryDate'] == "" ? NULL : $_POST['candidatePassportExpiryDate'];
    $candidatePlaceOfIssue = $_POST['candidatePlaceOfIssue'] == "" ? NULL : $_POST['candidatePlaceOfIssue'];
    $inMalaysia = $_POST['inMalaysia'] == "" ? NULL : $_POST['inMalaysia'];
    $visaCollectionCenter = $_POST['visaCollectionCenter'] == "" ? NULL : $_POST['visaCollectionCenter'];
    $candidatePermitType = $_POST['candidatePermitType'] == "" ? NULL : $_POST['candidatePermitType'];
    
    // Additional data for tbl_candidate_documents
    $documentTypeID = $_POST['documentTypeID'] == "" ? NULL : $_POST['documentTypeID'];

    // File upload handling
    $uploadDirectory = '/uploads/candidate_files/';
    $uploadedFilePath = NULL;

    echo "Candidate Name : " . $candidateName . "<br>";
    echo "candidate Nationality : " . $candidateNationality . "<br>";
    echo "Candidate Permit Type : " . $candidatePermitType . "<br>";
    echo "Candidate Document ID : " . $documentTypeID . "<br>";
    exit();



    
    
    if (isset($_FILES['candidateFile']) && $_FILES['candidateFile']['error'] == UPLOAD_ERR_OK) {
        $fileTmpPath = $_FILES['candidateFile']['tmp_name'];
        $fileName = $_FILES['candidateFile']['name'];
        $fileExtension = pathinfo($fileName, PATHINFO_EXTENSION);

        // Sanitize candidate name and passport number for the filename
        $sanitizedCandidateName = preg_replace("/[^a-zA-Z0-9]/", "_", $candidateName);
        $sanitizedPassportNo = preg_replace("/[^a-zA-Z0-9]/", "_", $candidatePassportNo);

        // Construct the new file name
        $newFileName = "{$sanitizedCandidateName}_{$sanitizedPassportNo}_Document.{$fileExtension}";
        $uploadedFilePath = $uploadDirectory . $newFileName;

        // Move file to the destination
        if (move_uploaded_file($fileTmpPath, $_SERVER['DOCUMENT_ROOT'] . $uploadedFilePath)) {
            // Insert file details into tbl_candidate_documents
            DB::insert('tbl_candidate_documents', [
                'candidate_id' => $candidateID,
                'document_type_id' => $documentTypeID,
                'permit_id' => $candidatePermitType,
                'document_name' => $newFileName,
                'document_path' => $uploadedFilePath,
                'status' => 1,
                'entry_user' => $username,
                'entry_date' => DB::sqlEval('NOW()')
            ]);
        } else {
            die('Error uploading file.');
        }
    }

    // Insert candidate details into tbl_candidate
    DB::insert('tbl_candidate', [
        'candidate_id' => $candidateID,
        'candidate_name' => $candidateName,
        'candidate_nationality' => $candidateNationality,
        'candidate_gender' => $candidateGender,
        'candidate_dob' => $candidateDOB,
        'candidate_age' => $candidateAge,
        'candidate_email' => $candidateEmail,
        'candidate_customer' => $candidateCompany,
        'candidate_passport_no' => $candidatePassportNo,
        'passport_issue_date' => $candidatePassportIssueDate,
        'passport_expiry_date' => $candidatePassportExpiryDate,
        'candidate_issue_place' => $candidatePlaceOfIssue,
        'candidate_is_in_malaysia' => $inMalaysia,
        'candidate_visa_collection_center' => $visaCollectionCenter,
        'candidate_permit_type_id' => $candidatePermitType,
        'status' => 1,
        'entry_user' => $username,
        'entry_date' => DB::sqlEval('NOW()')
    ]);

    break;

I am encountering an issue with receiving a null value for the Postman bearer token in a Laravel middleware

I am currently experiencing an issue with my Laravel API on a cPanel-hosted environment. When making API requests from Postman with a Bearer token in the Authorization header, the token is not being received by the application. This setup works as expected on my local environment, where the Bearer token is successfully passed and retrieved by the application. However, in the cPanel environment, the Authorization header appears to be missing or stripped out.

I have already tried the following troubleshooting steps:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
</IfModule>

<IfModule mod_headers.c>
    Header always set Access-Control-Allow-Origin "*"
    Header always set Access-Control-Allow-Headers "Authorization, Content-Type, X-Requested-With"
</IfModule>

I am getting a null value when trying to retrieve the Bearer token using $request->bearerToken() in middleware.

I am using cPanel for my hosting environment.

MouseEnter and MouseLeave target multiple elements on local host

I am developing a website in Kirby environment and I have been testing it on localhost. A function within this website creates a highlight for each .main element that acquires a color upon hovering and changes back upon mouse leaving.

I have encountered a very specific problem that occures upon mouse hovering. The problem overall is that I am trying to target one element, however upon howering the mouse it fires them all at the same time.

I have console logged the function and it seems like that the code indeed detects multiple .main elements being selected.

The function works as intended when I run it on HTML directly from Visual Studio Code. (The screenshot attached is from that version.)

What could be the issue?

<?php foreach ($page->articles()->toStructure() as $article): ?>
                <div class="main">
                  <div class="container" onclick="toggleSibling(this);">
                      <div class="Title"><?= $article->title() ?></div>
                      <div class="Genre"><?= $article->genre() ?></div>
                      <div class="Publisher"><?= $article->publisher() ?></div>
                      <div class="Datum"><?= $article->datum() ?></div>
                  </div>
                  <div class="content">
                                            <div class="Info">
                      <?= $article->info()->kt() ?>
                  </div>
                      <div class="Image">
                          <!-- <img src="content/test/painting-forest-lake.jpg"> -->
                          <div class="swiper">
                              <div class="swiper-wrapper">
                                  <?php foreach ($article->images()->toFiles() as $image): ?>
                                      <div class="swiper-slide">
                                          <img src="<?= $image->url() ?>" alt="<?= $image->alt() ?>">
                                      </div>
                                  <?php endforeach; ?>
                              </div>
                              <div class="swiper-scrollbar"></div>
                              <button class="slick-prev"></button>
                              <button class="slick-next"></button>
                          </div>
                      </div>
                      <div class="Page"></div>
                      <div class="Text">
                          <?= $article->text()->kt() ?>
                      </div>
              </div>
          <?php endforeach; ?>
document.addEventListener('DOMContentLoaded', () => {
  const mainElements = document.querySelectorAll('.main');
  const headerDivs = document.querySelectorAll('.container_header > div');

  const generateLightColor = () => {
    const randomValue = () => Math.floor(Math.random() * 156 + 100);
    return `rgb(${randomValue()}, ${randomValue()}, ${randomValue()})`;
  };

  mainElements.forEach(main => {
    const randomColor = generateLightColor();
    const container = main.querySelector('.container');
    const spans = main.querySelectorAll('span');

    console.log("Generated random color:", randomColor); 

    main.addEventListener('mouseenter', () => {
      container.style.backgroundColor = randomColor;
      document.documentElement.style.setProperty('--color-variable', randomColor);

      headerDivs.forEach(div => {
        div.style.backgroundColor = randomColor;
        div.style.color = container.style.color = 'black';
      });

      spans.forEach(span => {
        span.style.backgroundColor = randomColor;
        span.style.color = 'black';
      });

      console.log("Mouse entered main element:", main); 
    });

    main.addEventListener('mouseleave', () => {
      container.style.backgroundColor = 'var(--color-border-dark)';
      headerDivs.forEach(div => {
        div.style.backgroundColor = 'var(--color-border-dark)';
        div.style.color = container.style.color = 'var(--default-text-color)';
      });

      spans.forEach(span => {
        span.style.backgroundColor = 'transparent';
        span.style.color = 'inherit';
      });

      console.log("Mouse left main element:", main); 
    });
  });
});

I have tried multiple takes, but none of them lead to resloving the problem. A lead I got was it might have to do with dynamic content generation and duplicates.

How can i find the last full weekend of a Month?

$ts1=strtotime("last saturday of november 2024"); #Timestamp1
$ts2=strtotime("+1 day",$ts1); #Timestamp2
echo "Last Saturday: ".date("d.m.Y",$ts1); #30.11.2024
echo "Last Sunday: ".date("d.m.Y",$ts2);   #01.12.2024

With the PHP code above, i get the date of the last saturday and last sunday of november 2024.
But that is not a FULL weekend, because sunday is from the first of december!
So i need the weekend before, witch is a full weekend in the same month -> 23+24. November 2024.
Same problem if i need the first full weekend, witch is not ok in month september 2024, because first of september is a sunday! To be a full weekend, the first weekend must be 7+8. September.

In month october, all is ok, because last full weekend is at date 26+27, so saturday and sunday are not separated.
I can’t find a function in PHP doing that!
Any help?

Problem with redirect to public with Laravel in subfolder

I would like to put some Laravel projects in a subfolder but I have a problem. The example path is /var/www/html/laravelA and /var/www/html/laravelB. When I go to localhost/laravelA I see the file listing. I tried using standard htaccess to redirect to public

RewriteEngine On
RewriteCond %{REQUEST_URI} !^/public/
RewriteRule ^(.*)$ /public/$1 [L,QSA].

but is use causes a 404 apache2 error. I am running on apache2 installed on Debian.

I trying use this htaccess

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteRule ^(.*)$ public/$1 [L]
</IfModule>

but Laravel show 404 if there is no public in the url