MSSQL Stored Procedure Insert Arabic

I’m working in a existing MS SQL database with Collation as SQL_Latin1_General_CP1_CI_AS. The target column data type has been updated to NVARCHAR(MAX) and set collation to Arabic_CI_AI_KS_WS. Using the stored procedure to insert/update row the NVARCHAR(MAX) data type has been setup. The stored procedure is saving but the data is not in the correct format.

MS SQL MODIFY TARGET COLUMN

ALTER TABLE myTable ALTER  COLUMN cLineNotes nvarchar(max) COLLATE Arabic_CI_AI_KS_WS 

MS SQL STORED PROCEDURE

CREATE PROCEDURE spMyProcedure
   ... --3 more lines here
   @pcLineNotes nvarchar(max)
AS
BEGIN 
   SET NOCOUNT ON;
   ... -- more lines here
   INSERT INTO myTable (cLineNotes ) VALUES (@pcLineNotes )
   ... -- more lines here
END

PHP Connection Info Using UTF-8

$connectionInfo = array("Database" => $this->db_name, "UID" => $this->db_user, "PWD" => $this->db_pwd , "CharacterSet" => "UTF-8");

PHP Stored Procedure Call

   $query = "{CALL  spMyProcedure( ?,?,?,?  )}"; 

   $params = array(
          array($param1, SQLSRV_PARAM_IN,),
          array(&$param2, SQLSRV_PARAM_IN),
          array(&$param3, SQLSRV_PARAM_IN),
          array(&$cLineNotes, SQLSRV_PARAM_IN)
   );

Sample cLineNotes value is اختبار يونيكود and stored value in database ط§ط®طھط¨ط§ط± ظٹظˆظ†ظٹظƒظˆط¯

How to retrieve the most frequent occurrences of a sub-value from an SQLITE database with comma-separated values in a column?

I have an SQLITE database with a table named “articles.” Each row in the “articles” table represents an article, and there is a column called “keywords” that contains the categories which the article is associated with, separated by commas (up to a maximum of 5 categories per article).

I am trying to find a way to retrieve the top 10 most popular categories based on the number of articles they are associated with. Essentially, I want to count the occurrences of each category across all articles and then display the top 10 categories.

Here is a simplified structure of my “articles” table:

CREATE TABLE IF NOT EXISTS articles 
(articleID TEXT PRIMARY KEY, 
title TEXT, 
author TEXT, 
keywords TEXT, 
content TEXT, 
description TEXT, 
date TEXT, 
reads INTEGER, 
hearts INTEGER, 
comments TEXT)

Is it possible to achieve this using an SQL query or any other method? If so, how can I do this?

I appreciate any guidance or examples to help me solve this problem. Thank you!

I have tried traditional SQL methods, but most are not successful.

WordPress Shortcode to calculate age in years, months and days

I have two PHP codes to calculate age in years, months and days

code I:

<?php
$dob = new DateTime('1978-09-29');
$today = new DateTime;
$age = $today->diff($dob);
echo $age->format('%y year, %m months dan %d days');
?>

code II:

<?php $dob = new DateTime('1978-09-29');
    $today   = new DateTime('today');
    $year = $dob->diff($today)->y;
    $month = $dob->diff($today)->m;
    $day = $dob->diff($today)->d;
    echo "Age is"." ".$year. " year"." ",$month. " months"." ".$day. " days";
?>

Can anyone help me? how to make the php code into a shortcode for wordpress.

PHP mb_convert_encoding turns ‘blue’ into ‘扬略’

I’m encountering a strange behavior when using mb_convert_encoding in PHP.
I have a variable $input containing the string ‘blue’, and when I try to convert it to UTF-8 using the following code:

$input = 'blue';
$str = mb_convert_encoding((string)$input, 'UTF-8', mb_list_encodings());

The resulting value of $str is ‘扬略’ instead of ‘blue’.
Can someone please help me understand what might be causing this unexpected transformation and how I can resolve it?

The script cannot be run because it is owned by a service account. Please copy or transfer the project to a valid account before running

I have the following issue. Through PHP, I create a copy of a Google Doc

$documentId = 'ID';
$googleAccountKeyFilePath = __DIR__ . '/service_key.json';
putenv('GOOGLE_APPLICATION_CREDENTIALS=' . $googleAccountKeyFilePath);
$client = new Google_Client();
$client->setApplicationName('Some name');
$client->setScopes([Google_Service_Docs::DOCUMENTS, Google_Service_Drive::DRIVE]);
$client->setAccessType('offline');
$client->setAuthConfig($googleAccountKeyFilePath);
$driveService = new Google_Service_Drive($client);
$originalDocument = $driveService->files->get($documentId);
$copyDocument = new Google_Service_Drive_DriveFile(array('name' => $_GET['domain'].' Title: ' . $_GET['date_start'].' - '.$_GET['date_end']));
$newDocument = $driveService->files->copy($documentId, $copyDocument); //copying document
$newDocumentId = $newDocument->getId();
$driveService->permissions->create($newDocumentId, new Google_Service_Drive_Permission(array('type' => 'anyone', 'role' => 'writer')));

The document is successfully created, and it contains an AppScript attached to the original, for example:

function onOpen() {
  const ui = DocumentApp.getUi();
  ui.createMenu('Addition')
    .addItem('findSynonyms', 'findSynonyms')
    .addToUi();
}

But the menu item does not appear, and when manually started, there’s an error:
Error
The script cannot be run because it is owned by a service account. Please copy or transfer the project to a valid account before running.

How can I fix this? What am I doing wrong? I am a bit far from all the policies of rights in App Scripts. If you can explain in more detail, I would be very grateful!”

appsscript.json:

{
  "timeZone": "Europe/Kiev",
  "dependencies": {
    "enabledAdvancedServices": [{
      "userSymbol": "Docs",
      "serviceId": "docs",
      "version": "v1"
    }, {
      "userSymbol": "Drive",
      "serviceId": "drive",
      "version": "v3"
    }]
  },
  "webapp": {
    "access": "DOMAIN",
    "executeAs": "USER_ACCESSING"
  },
  "exceptionLogging": "STACKDRIVER",
  "runtimeVersion": "V8"
}

PHP: Keep specific keys/values in array, remove all others

With an array like this:

[
   ['id' => 1, 'name' => text, 'description' => "desc 1", +50 keys/values...]
   ['id' => 1, 'name' => text, 'description' => "desc 1", +50 keys/values...]
   ['id' => 1, 'name' => text, 'description' => "desc 1", +50 keys/values...]
   and more...
]

How can i get this result:

[
   ['id' => 1, 'name' => text, 'description' => "desc 1"]
   ['id' => 1, 'name' => text, 'description' => "desc 1"]
   ['id' => 1, 'name' => text, 'description' => "desc 1"]
   and more...
]

So the same array but without the 50 array/keys remaining ?

I know i can use unset() on the 50 keys not needed to remove them from the array but i’m looking for a maybe better/clean way to do it. Otherwise i would make a lot of unset to do just for keeping 3 keys.

Woocommerce. How to hide some categories and subcategories on the shop main page, catalog pages (archive, categories and subcategories pages)

I need to hide (not disable, the category link should open as usual) certain categories in the list of categories and subcategories Woocommerce on the shop main page, catalog pages (archive, categories and subcategories pages):

  • If there are no products in this category
  • If all products in this category are Out of stock
  • If all products in this category are Catalog visibility: Hidden

I found a solution for this for the main store page, however, on the product category and archive counters, this solution completely removes all subcategories.

function hide_empty_categories( $terms, $taxonomies, $args ) {
$new_terms = array();

foreach ( $terms as $key => $term ) {

if ( is_object( $term ) ) {

if ( $term->count > 0 ) {
$new_terms[] = $term;
}
}
}

return $new_terms;
}

add_filter( 'get_terms', 'hide_empty_categories', 10, 3 );

PS. There is no problem in the widget of categories and subcategories of products that are in the sidebar. There, the standard settings hide such categories, the problem is in the main place of displaying categories and subcategories

Has anyone found the solution to set the product Catalog visibility: Hidden? How to use it in a way that it affected the categories (and not just the product)?

I contacted Woocommerce support, where they told me that there are no standard solutions for this. I also tried to use different codes, the one given above, but it does not work correctly

Month equivalence and unit restriction in forHumans function

I’m encountering two peculiar behaviors with a library, and my objective is to convert seconds into a readable format displaying days, hours, minutes, and seconds.

When attempting to convert 2698447 seconds into a human-readable format using the Carbon library, I obtain the following result:

<?php

use CarbonCarbonInterval;
use CarbonCarbon;

echo CarbonInterval::seconds(2698447)->cascade()->forHumans();

enter image description here

However, when using an online converter, the output is different (https://www.tools4noobs.com/online_tools/seconds_to_hh_mm_ss/):

Online Converter Result

In my code, I also experimented with CarbonInterval, and when converting 28 days and 30 days separately, the output seems to imply that 28 days is equivalent to a month:

use CarbonCarbonInterval;
use CarbonCarbon;

echo CarbonInterval::seconds(28*24*3600)->cascade()->forHumans(); // Outputs: 28 days
echo "n";
echo CarbonInterval::seconds(30*24*3600)->cascade()->forHumans(); // Outputs: 30 days
echo "n";

CarbonInterval Results

Considering these results, I am puzzled about the interpretation of days as a month. How can I configure the conversion to consider a month as 30 or 31 days, and furthermore, is it possible to restrict the output to days as the maximum unit (days hours minutes seconds)?

How can I remove all spaces from the beginning and end of each line using regex? [duplicate]

In the client-side, the user will write his bio and pass it to the API. Now, I expect that when the user writes his bio, I want to store it in the database like this:

Vivamus feugiat orci sed posuere sodales. Praesent in tincidunt ligula.

Sed ac nisl ipsum. Phasellus et ipsum quis metus blandit vestibulum. Praesent et ligula sodales, ornare lectus in, pellentesque orci.

Phasellus accumsan tristique libero, bibendum convallis augue dapibus vel.

As you can see, there are no multiple white spaces in the bio, only one white space is allowed.

Now, I receive the bio from the client-side like this: (regex101.com)

enter image description here

As you can see, there are multiple white spaces in this bio, and these multiple white spaces are unnecessary.

To clean unnecessary white spaces, I used trim() to remove all white spaces from the beginning and end of the string. However, that is not enough. I also want to remove all spaces from the beginning and end of each line, and here is what I tried:

<?php
echo preg_replace("/(?:^( )+)|(?:( )+$)/m", "$1$2", trim($_POST["bio"]));

Now the question is, is it possible to change $1 and $2 to nothing, like this -> "", instead of becoming -> " "?

You may suggest replacing the second parameter of preg_replace from "$1$2" to "". However, I don’t want this solution because I still need to play with regex later to remove other multiple white spaces such as ntrv and replace them with one.

So, let’s go back to my question. I need to tell the regex that when I say $1 and $2, I want it to replace with "" and not with " ". Is it possible?

Note: I hope you don’t close this question just because I left an image instead of text. I tried this, but it is hard to make it readable for users. Therefore, I included a URL of regex on regex101.com.

Compare values ​between two arrays [closed]

I called the values ​​from the database by the following commands:

<?php
$server = "localhost";
$user = "root";
$pass = "root";
$database = "elahieh33"; 
$con = mysqli_connect($server, $user, $pass);
$con->set_charset("utf8");
if(!$con){
    echo 'Server not connected';
}
$db = mysqli_select_db($con, $database);
if(!$db){
    echo 'Database not connected';
}

$result = $con->query("SELECT id FROM `wp_posts` WHERE post_type = 'shop_order' ");
$result1 = $con->query("SELECT post_id FROM `wp_postmeta` WHERE meta_key = '_billing_first_name' ");


$r = array();
if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {

        $r[] = $row;        
    }     
}

$r1 = array();
if ($result1->num_rows > 0) {
    while ($row1 = $result1->fetch_assoc()) {

        $r1[] = $row1;  
    }     
}

Now I want to compare the values ​​of two arrays and show the common values, I use the following command to compare the values, but I don’t get the correct answer:

$result2 = array_intersect($r, $r1);
print_r($result2);

Error message after executing the last command: “Notice: Array to string conversion”

please guide me.

Permission denied for unix socket mounted in docker container as volume

I try to containerize my nginx running currently on my server. For this I created the following docker compose file:

version: "3.8"
services:
  nginx:
    image: nginx:stable-alpine
    container_name: nginx
    restart: unless-stopped
    group_add: ["33"]
    volumes:
      - "/etc/nginx-docker:/etc/nginx/conf.d:ro"
      - "/run/php:/run/php"
      - "/var/www:/var/www:ro"
    ports:
      - "8111:80"
      - "8443:443"

Everything works fine but the problem is, that I still have php-fpm’s running on my host system and I want to use their sockets for my nginx container (hence the line volumes: - "/run/php:/run/php").

The sockets’ permissions are srw-rw---- www-data:www-data. Therefore I added the container user to the group 33 (which is www-data on my host system -> group_add: ["33"]). When I check in the container the group ids, the id 33 is indeed added to the currently logged in user:

/ # id -G
0 1 2 3 4 6 10 11 20 26 27 33
/ # id -u
0
/ # whoami
root

Nonetheless when I call a website powered by PHP I get in the nginx logs following error message:

2024/01/21 08:58:53 [crit] 21#21: *1 connect() to unix:/run/php/php8.2-fpm.sock failed (13: Permission denied) while connecting to upstream, client: 192.168.192.68, server: _, request: "GET / HTTP/1.1", upstream: "fastcgi://unix:/run/php/php8.2-fpm.sock:", host: "op---s:8111"

Any hints or solutions what could be missing to make it work?

Duplicate form using alpinejs and livewire

I want to duplicate a form using alpinejs and there is another form that can be duplicated inside this parent form. I’m doing very well so far. In the child form, there is a and its content depends on the choice in the parent form. Clicking on a choice in the parent form triggers a function call that fetches the corresponding results from the back end, and these results are used as choices in the child form.
How do I fill in and manage the choice in this child form?

here is my livewire component:
view:

<div>
    <form action="" x-data="{
        produits: @entangle('produits'),
    
        getNextId(items) {
            const ids = items.map(item => item.id);
            return ids.length > 0 ? Math.max(...ids) + 1 : 1;
        },
    
        duplicateProduct() {
            // const newProduct = JSON.parse(JSON.stringify(this.produits[0]));
            const defaultProduct = {
                id: this.getNextId(this.produits),
                produit: '',
                masses: [{
                    id: 1,
                    masse_unite: '',
                    nombre: '',
                }],
            };
            // newProduct.id = this.getNextId(this.produits);
            this.produits.push({ ...defaultProduct });
        },
    
        duplicateMasse(productIndex) {
            const product = this.produits[productIndex];
            const newMasse = { id: this.getNextId(product.masses), masse_unite: '', nombre: '' };
            product.masses.push(newMasse);
        },
    
        removeProduct(productIndex) {
            if (this.produits.length > 1) {
                this.produits.splice(productIndex, 1);
            }
        },
    
        removeMasse(productIndex, masseIndex) {
            const product = this.produits[productIndex];
            if (product.masses.length > 1) {
                product.masses.splice(masseIndex, 1);
            }
        },
    }">
        <div class="flex justify-start">
            <div class="">
                <label for="" class="text-gray-700">Date</label>
                <div class="relative mt-1 mb-3" data-te-input-wrapper-init id="datepicker-disabled-dates"
                    data-te-format="dd mmmm yyyy">
                    <input type="text"
                        class="peer block min-h-[auto] w-full rounded border-0 bg-transparent px-3 py-[0.32rem] leading-[1.6] outline-none transition-all duration-200 ease-linear focus:placeholder:opacity-100 peer-focus:text-primary data-[te-input-state-active]:placeholder:opacity-100 motion-reduce:transition-none dark:text-neutral-200 dark:placeholder:text-neutral-200 dark:peer-focus:text-primary [&:not([data-te-input-placeholder-active])]:placeholder:opacity-0"
                        placeholder="Select a date" />
                </div>
            </div>
        </div>
        <hr class="my-6">
        <template x-for="(product, productIndex) in produits" :key="product.id">
            <div>
                <div class="inline-flex w-full items-center mb-4 pr-3">
                    <h4 class="underline">Article #<span x-text="productIndex + 1"></span></h4>
                    <button type="button" @click="removeProduct(productIndex)" x-show="produits.length > 1"
                        class="text-red-500 items-center ml-6 hover:underline hover:underline-offset-2">Supprimer</button>
                </div>
                <div class="grid grid-cols-3 gap-4">

                    <div>
                        <x-input-label ::for="'produit_' + product.id" :value="__('Produit')" />
                        <select name="produit" :id="'produit_' + product.id" wire:change='getMasseUnite(productIndex)'
                            x-model='product.produit'
                            class="w-full mt-1 rounded focus:border-blue-400 focus:ring-blue-400 focus:outline-none border-gray-300">
                            <option value="">--- Sélectionner ---</option>
                            @foreach ($stocks as $stock)
                                <option value="{{ $stock->produit_id . ',' . $stock->purete_id }}">
                                    {{ $stock->produit->nom . ' ' . formatFrenchNumber($stock->purete->purete) . ' %' }}
                                </option>
                            @endforeach
                        </select>
                    </div>
                    <div class="col-span-2 ml-6">
                        <template x-for="(masse, masseIndex) in product.masses" :key="masse.id">
                            <div class="grid grid-cols-2 gap-4 mb-4">
                                <div>
                                    <x-input-label ::for="'masse_bloc_' + masse.id" :value="__('Masse/bloc')" />
                                    <select name="masse_bloc" :id="'masse_bloc_' + masse.id" x-model=masse.masse_unite
                                        class="w-full mt-1 rounded focus:border-blue-400 focus:ring-blue-400 focus:outline-none border-gray-300">
                                        @if (!is_null($masses['productIndex']))
                                            @foreach ($masses['productIndex'] as $masse)
                                                <option value="">{{ $masse->masse_unite . ' g' }}</option>
                                            @endforeach
                                        @endif
                                    </select>
                                </div>
                                <div>
                                    <x-input-label ::for="'nbr_masse_bloc_' + masse.id" :value="__('Nombre')" />
                                    <div class="inline-flex items-center space-x-3 w-full">
                                        <x-text-input ::id="'nbr_masse_bloc_' + masse.id" name="nbr_masse_bloc" x-model="masse.nombre"
                                            type="text" class="mt-1 block w-full" required placeholder='12' />
                                        <button type="button" class="text-red-500 transition-transform hover:scale-110"
                                            x-show="product.masses.length > 1"
                                            @click="removeMasse(productIndex, masseIndex)">
                                            <svg data-slot="icon" fill="none" class="w-5 h-5" stroke-width="1.5"
                                                stroke="currentColor" viewBox="0 0 24 24"
                                                xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
                                                <path stroke-linecap="round" stroke-linejoin="round"
                                                    d="m14.74 9-.346 9m-4.788 0L9.26 9m9.968-3.21c.342.052.682.107 1.022.166m-1.022-.165L18.16 19.673a2.25 2.25 0 0 1-2.244 2.077H8.084a2.25 2.25 0 0 1-2.244-2.077L4.772 5.79m14.456 0a48.108 48.108 0 0 0-3.478-.397m-12 .562c.34-.059.68-.114 1.022-.165m0 0a48.11 48.11 0 0 1 3.478-.397m7.5 0v-.916c0-1.18-.91-2.164-2.09-2.201a51.964 51.964 0 0 0-3.32 0c-1.18.037-2.09 1.022-2.09 2.201v.916m7.5 0a48.667 48.667 0 0 0-7.5 0">
                                                </path>
                                            </svg>
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </template>
                        {{-- bouton ajouter d'autre masse bloc --}}
                        <div class="flex w-full justify-end items-center">
                            <div class="mb-3 mt-5">
                                <button type="button" @click="duplicateMasse(productIndex)"
                                    class="text-blue-500 inline-flex items-center hover:underline hover:underline-offset-2">
                                    <svg fill="none" class="w-5 h-5 mr-2" stroke="currentColor" stroke-width="1.5"
                                        viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
                                        <path stroke-linecap="round" stroke-linejoin="round"
                                            d="M12 9v6m3-3H9m12 0a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                                    </svg>
                                    Ajouter un autre bloc
                                </button>
                            </div>
                        </div>
                    </div>
                    <hr class="mb-4 col-span-3" x-show="produits.length > 1 && produits.length != productIndex + 1">
                </div>
            </div>
        </template>

        <div class="mb-3">
            <button type="button" @click="duplicateProduct()"
                class="text-blue-500 inline-flex items-center hover:underline hover:underline-offset-2">
                <svg fill="none" class="w-5 h-5 mr-2" stroke="currentColor" stroke-width="1.5" viewBox="0 0 24 24"
                    xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
                    <path stroke-linecap="round" stroke-linejoin="round"
                        d="M12 9v6m3-3H9m12 0a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                </svg>
                Ajouter d'autre produit
            </button>
        </div>
        {{-- <hr class="my-3">
        <div class="grid grid-cols-5 pt-3 gap-x-4">
            <div>
                <x-input-label for="type_transformation" :value="__('Transformer en')" />
                <select name="type_transformation" id="type_transformation"
                    class="w-full mt-1 rounded focus:border-blue-400 focus:ring-blue-400 focus:outline-none border-gray-300">
                    <option value="">Lingot</option>
                    <option value="">barette</option>
                    <option value="">Bille</option>
                </select>
            </div>
            <div>
                <x-input-label for="dimension" :value="__('Dimension')" />
                <x-text-input id="dimension" name="dimension" type="text" class="mt-1 block w-full" required
                    placeholder='100 x 400 x 25' />
            </div>
            <div>
                <x-input-label for="purete_attendue" :value="__('Purété final')" />
                <x-text-input id="purete_attendue" name="purete_attendue" type="text" class="mt-1 block w-full"
                    placeholder='99,99%' />
            </div>
            <div>
                <x-input-label for="masse_unite_final" :value="__('Masse par Unité')" />
                <x-text-input id="masse_unite_final" name="masse_unite_final" type="text"
                    class="mt-1 block w-full" placeholder='2 150 g' />
            </div>
            <div>
                <x-input-label for="nombre_final" :value="__('Nombre')" />
                <x-text-input id="nombre_final" name="nombre_final" type="text" class="mt-1 block w-full"
                    placeholder='25' />
            </div>
        </div> --}}

        <div class="flex items-center justify-end space-x-6 mt-6">
            <button type="button"
                class="inline-block rounded bg-primary-100 px-6 pb-2 pt-2.5 text-xs font-medium uppercase leading-normal text-primary-700 transition duration-150 ease-in-out hover:bg-primary-accent-100 focus:bg-primary-accent-100 focus:outline-none focus:ring-0 active:bg-primary-accent-200">
                Annuler
            </button>
            <button type="button"
                class="inline-block rounded bg-primary px-6 pb-2 pt-2.5 text-xs font-medium uppercase leading-normal text-white shadow-[0_4px_9px_-4px_#3b71ca] transition duration-150 ease-in-out hover:bg-primary-600 hover:shadow-[0_8px_9px_-4px_rgba(59,113,202,0.3),0_4px_18px_0_rgba(59,113,202,0.2)] focus:bg-primary-600 focus:shadow-[0_8px_9px_-4px_rgba(59,113,202,0.3),0_4px_18px_0_rgba(59,113,202,0.2)] focus:outline-none focus:ring-0 active:bg-primary-700 active:shadow-[0_8px_9px_-4px_rgba(59,113,202,0.3),0_4px_18px_0_rgba(59,113,202,0.2)] dark:shadow-[0_4px_9px_-4px_rgba(59,113,202,0.5)] dark:hover:shadow-[0_8px_9px_-4px_rgba(59,113,202,0.2),0_4px_18px_0_rgba(59,113,202,0.1)] dark:focus:shadow-[0_8px_9px_-4px_rgba(59,113,202,0.2),0_4px_18px_0_rgba(59,113,202,0.1)] dark:active:shadow-[0_8px_9px_-4px_rgba(59,113,202,0.2),0_4px_18px_0_rgba(59,113,202,0.1)]">
                Enregistrer
            </button>
        </div>
    </form>
</div>

livewire:

<?php

namespace AppLivewireTransformation;

use AppModelsStock;
use LivewireComponent;

class NewTransformation extends Component
{
    public $date_transformation;
    public $produits = [
        [
            'id' => 1,
            'produit' => '',
            'masses'=> [
                [
                    'id' => 1,
                    'masse_unite' => '',
                    'nombre' => '',
                ]
            ],
        ]
    ];
    public $stocks;
    public $masses = [];

    public function mount() {
        $this->stocks = Stock::select('produit_id', 'purete_id')
                            ->groupBy('produit_id', 'purete_id')
                            ->with('produit', 'purete')
                            ->orderBy('produit_id')
                            ->orderBy('purete_id')
                            ->get();
    }

    public function render()
    {
        return view('livewire.transformation.new-transformation');
    }

    public function getMasseUnite($index) {
        $prod = $this->produits[$index];

        $arrayId = explode(',', $prod['produit']);

        $this->masses[$index] = Stock::where('produit_id', $arrayId[0])
                    ->where('purete_id', $arrayId[1])
                    ->get();
    }
}

Can not install MongoDB driver for PHP using XAMPP

I try to install the php drivers for MongoDB on my local environment but can not get it to run.

I downloaded the latest version (an every variation of this version because I got desperate), putted the driver in the exp/ folder and updated the extension=mongodb line in the php.ini (here I tried extension=php_mongodb.dll as well)

Nothing seems to work and my apache error log logged this error:
PHP Warning: PHP Startup: Unable to load dynamic library ‘mongodb’ (tried: C:xamppphpextmongodb

I wonder if it is because of the double backslashes but I have no idea where to fix it. Every other extensions is loaded normally.

My PHP version ist 8.2.12 on an x64 architecture.

Do you have any idea what the solution can be?

How come Laravel .env variables display in browser but return NULL in PHP scripts run in the CLI?

I’m developing a web app using Laravel. I’ve set an API key in my .env file, which is correctly placed in the root directory. I’m able to retrieve and view the API key in the browser using a test route:

Route::get('/test-env', function () {
    $envValue = env('OPEN_AI_KEY');

    return "Environment Variable Value: $envValue";
});

However, when I try to run one of my crucial business logic scripts in my CLI, which includes the identical env(‘[MY_ENV_KEY]’) function and parameter, I get NULL returned.

I’ve tested with several environment keys, and all of them show up in the browser using the /test-env route, but all return NULL in my CLI.

I have tried using iTerm2 and the VSCode terminal to rule out a problem with the particular CLI.

I’ve tried getenv() instead, which also works in my /test-env route but returns bool(false) for all .env keys in my CLI.

For reference, this is the relevant portion of the class that is instantiated in the script I’m trying to run in my CLI:

$openAiKey = env('OPEN_AI_KEY');

        var_dump($openAiKey);
        exit;

As recommended per similar questions, I’ve tried running:

php artisan config:clear
php artisan cache:clear
php artisan optimize:clear 

I’ve also tried restarting my development server.

I’m expecting the value of the .env key to show up in the CLI, confirming that the script is successfully fetching it, just as the /test-env route can, but I keep getting NULL or bool(false).