Validation error message do not match log error message in Laravel excel validation

How can I resolve an issue where my log error messages are correct, but the validation error messages displayed to the user show a different dose number than expected? Here’s my code for logging and validating doses for vaccines, but the row number in the validation errors doesn’t match the log output.


public function withValidator($validator)
    {
        $validator->after(function ($validator) {
            $data = $validator->getData();

            foreach ($data as $key => $row) {
                $vaccine = $row['vaccine'];
                Log::info('$vaccine'.$vaccine);
                $inventory = Inventory::where('name', $vaccine)->where('inventory_type_id', 15)->first();

                if (!$inventory) {
                    Log::error("The vaccine '{$vaccine}' does not exist.");
                    $validator->errors()->add("vaccine", "The vaccine '{$vaccine}' does not exist.");
                } else if (isset($row['given_doses']) && (int)$row['given_doses'] > (int)$inventory->dose_numbers) {
                    $totalDoses=$inventory->dose_numbers;
                    $message="The DOSE set for '$inventory->name.' is  '$totalDoses' any dose given above '{$totalDoses}' should not be added.";
                    Log::info("Dose numbers for '{$inventory->name}': {$totalDoses}");
                    Log::info("Processing row {$key}: Vaccine ' {$vaccine}', Given Doses: '{$row['given_doses']}', Inventory Dose Numbers: '{$inventory->dose_numbers}'");

                    Log::error($message);
                    $validator->errors()->add($key, $message);
                }
            }
        });
    }

Here is the output of my log

[2024-09-05 13:59:08] local.INFO: Dose numbers for ‘FMD’: 25
[2024-09-05 13:59:08] local.INFO: Processing row 2: Vaccine ‘ FMD’, Given Doses: ’30’, Inventory Dose Numbers: ’25’
[2024-09-05 13:59:08] local.ERROR: The DOSE set for ‘.FMD.’ is ‘.25.’ any dose given above ’25’ should not be added.

and here is the message displayed in the view
There was an error on row 2. The DOSE set for ‘FMD.’ is ‘5’ any dose given above ‘5’ should not be added.

It should print the exact numbers of doses in both messages. Log is displaying corrext values and view is not.

How to calculate pay rate from worked time without using if statement

I am trying to calculate workers pay rate from their worked time. For example if workers go to each client house the number of hours or minutes or hours and minute they spent there, the rate will be calculated from a fixed pay rate($10).
Bellow is the code I was able to create

 $varWorkHour = '00:30';
    $varPayRate = 10.00;
    $varWorkTime = 10.00;
    if ($varWorkHour == '1:00') {
        $varWorkTime = (100 / 100) * $varPayRate;
    } else if ($varWorkHour == '00:45') {
        $varWorkTime = (85 / 100) * $varPayRate;
    } else if ($varWorkHour == '00:30') {
        $varWorkTime = (50 / 100) * $varPayRate;
    } else if ($varWorkHour == '00:15') {
        $varWorkTime = (15 / 100) * $varPayRate;
    }


    echo $varWorkTime;

The code worked
But the problem is I don’t want to use if statement, as you can see the code is limited to 1 hour below and there are some cases where workers can work up to 5 hours and more. Using if statement on that will be exhausting.
Please how can I calculate the pay rate from worked time dynamically without using if statement.

how i learn node js after working with laravel for 2 years

Title: How can I transition from Laravel PHP to building production-level applications with Node.js?

Question: I’ve been working with Laravel and PHP for a while, but now I’m looking to switch my tech stack to Node.js. While I have a basic understanding of Node.js and Vue.js, I’m aiming to build production-level applications.

Could you suggest a learning path and key steps to follow for mastering Node.js? Specifically, I want to learn:

Best practices for building scalable, maintainable Node.js applications.
How to structure large Node.js projects, especially in the context of full-stack applications.
Essential tools and libraries (e.g., Express.js, authentication, security, etc.) for building production-level systems.
Tips on transitioning from Laravel to a Node.js ecosystem and how I can leverage my existing knowledge.

Any recommended resources, courses, or guidelines for this transition would be appreciated!

How to map exceptions to repsonse http status code in PHP [closed]

While API development I tried to guess the response status code of requests in a error handler. In most of the known frameworks in the PHP universe there is an error handler, where I get a Throwable and there is a Throwable::getCode() (documentation).

From my point of view this code is more an identifier, than a status code. My best practice is using the current timestamp as code, so I can find the corresponding place in my source code very fast. If I need a return status code I would extend the exception and add a statusCode property.

After a research I saw so many solutions, where developers use the code as return status code. So I am interested in a something like a default PHP exception mapper to status code without using the existing code as status code or at least a best practice to do so. Is there a open source solution or am I on the wrong path?

Laravel error with php artisan migrate in mysql

Can you help me with this error? I can’t migrate my file in mysql.
I’m running the latest version of laravel when i migrate in the terminal.

When i run:

php artisan migrate

I get the following error:
SQLSTATE[HY000]: General error: 1005 Can’t create table agricultures1.archives (errno: 150 “Foreign key constraint is incorrectly formed”) (Connection: mysql, SQL: alter table archives add constraint archives_farmers_id_foreign foreign key (farmers_id) references farmers (id) on delete cascade)

Auto Update Not Working On Filament Table Widget

I’m using a service that makes an API call to return data for me. I would like this data to be updated every 60 seconds. I’m aware that by default, widgets update every 10 seconds, however, my data doesn’t seem to ever update after it’s initial load.

I currently have this within my TopPages widget:

public function table(TablesTable $table): TablesTable
    {
        return $table
            ->query(TopPage::query())
            ->columns([
                TextColumn::make('page')
                    ->label('Page')
                    ->getStateUsing(fn ($record) => $record['page']),
                TextColumn::make('visitors')
                    ->label('Visitors')
                    ->getStateUsing(fn ($record) => number_format($record['visitors'])),
                TextColumn::make('pageviews')
                    ->label('Page Views')
                    ->getStateUsing(fn ($record) => number_format($record['pageviews'])),
            ]);
    }

and this within my TopPage model:

use Sushi;

    protected $rows;

    public function getRows(): array
    {
        $plausibleAnalyticsService = new PlausibleAnalyticsService();

        $topPages = $plausibleAnalyticsService->fetchTopPages();

        Log::info('TopPage model getRows method called');

        return $topPages;
    }

How can I have my data update every 60 seconds? I’ve tried adding the following, but it doesn’t seem to make the api call ever again:

->poll('60s');

Delete messages in a telegram bot

I’m writing a telegram bot to delete spam from a channel where the bot is administrator (with permission to delete messages)

I’m doing some tests using PHP and telegram-bot-sdk 2.0

I’m able to answer to messages using the bot, but if I try to delete a specific message nothing happens, and the method always returns false

require 'vendor/autoload.php';
use TelegramBotApi;
$client = new Api('[api key here]');
$last_update_id=0;
while(true){
    $response = $client->getUpdates(['offset'=>$last_update_id, 'timeout'=>5]);
    if (count($response)<=0) continue;
    foreach ($response as $r){

        //Get the message somebody sent
        $last_update_id=$r->getUpdateId()+1;
    $message=$r->getMessage();
        $messageId = $message['message_id'];
    $chat = $message['chat'];
    $chatId = $chat['id'];
        
        //Log to console the message received
        echo "Somebody said: ".$message['text']." with message id: ".$messageId." on chat ".$chatId."n";
        
        //Answering works
        $ret = $client->sendMessage(['chat_id' => $chatId, 'text' => 'I'm deleting your message!']);
    
        //Deleting doesn't work
    $ret = $client->deleteMessage([ 'chat_id' => $chatId, 'message_id' => $messageId]);
    echo "ret:".($ret?"true":"false");
    }
}

Any Advice?

I’m not even 100% sure deleteMessage() is a method of $client (according the documentation it seems so, but it’s not totally clear) because if it mispell the method on purposes like deleteMessagx() I get false and no error.

Trying to use MAMP and accessing phpMyAdmin returns en error “mysqli is missing” [duplicate]

It all started a couple days ago trying to setup Hesk via MAMP. It was giving me an error during installation I honestly cannot remember, so I decided to try reinstalling MAMP and see if it weould fix the problem.

Now it’s worse than before, I; ve done multiple clean reainstall (also tried re-downloading the setup) but every time I try to access phpMyAdmin it gives me always the same error, which is:

“The mysqli extension is missing. Please check your PHP configuration. See our documentation for more information.”

I’m pretty new to this, so I have honestly no clue on where I can even start looking for a solution in a case like that.

The fact that disturbs me more is that before all that it was working, maybe I was using an older MAMP version? I honestly dont know.
I’ve also done a clean unistall helping me with Revo to remove every possible thing left, and it didnt help either.

Get origin $_SERVER[‘HTTP_ORIGIN’] cors whitelist domain name get origin is null?

$origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : null;

header("Access-Control-Allow-Origin: $allowed_domain");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Headers: Content-Type, Accept, Authorization");
header("X-Frame-Options: ALLOW-FROM $origin");
header("Content-Security-Policy: frame-ancestors 'self' $allowed_domain");

this code origin cors whitelist domain, but get $origin all null?

Why I can’t get supervisord recognize new .conf files in Laravel Sail/Docker installation?

so I’ve got a scout-worker.conf in /etc/supervisor/conf.d It contains this code:

[program:scout-worker]
process_name=%(program_name)s_%(process_num)02d
command=docker exec cercasemi-laravel.test-1 php /var/www/html/artisan queue:work redis --queue=scout --sleep=3 --tries=3
autostart=true
autorestart=true
stopasgroup=true
killasgroup=true
user=root
numprocs=1
redirect_stderr=true
stdout_logfile=/var/www/html/storage/logs/scout-worker.log

But when I issue a command like this, it doesn’t recognize the new scout-worker.conf:

docker exec cercasemi-laravel.test-1 supervisorctl reread

Why?

PHP executed success query echo breaks favicon

On all my pages I am echoing a success alert if the query was successfully executed, similarly if it does not there is an error message also echoed.

I have noticed every time the query has ran, and the echo is performed, it is breaking the favicon (i.e. the favicon icon does not load and the default grey globe is appearing). It also triggers Quriks Mode.

What methods can be utilised to echo deeper into the HTML (after all meta tags, scripts etc…) rather than at the very top of the opening body tag.

The favicon loads fine when laoding the page before any query is executed and after testing it is the echo that is causing this issue.

if($stmt->execute()) {
    
echo '<div class="alert alert-success alert-dismissible fade show notif-alert" role="alert">';
echo '<strong>Success!</strong> Password was changed successfully!';
echo '<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>';
echo '</div>';

} else { 

echo '<div class="alert alert-warning alert-dismissible fade show notif-alert" role="alert">';
echo '<strong>Error!</strong> An error occured, please try again!';
echo '<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>';
echo '</div>';
echo "Error: " . $stmt->error;
    
}

After the echo you can see where the div is being inserted

<body>
<div class="alert alert-success alert-dismissible fade show notif-alert" role="alert"><span><strong>Success!</strong> User information updated successfully!</span><button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button></div>

<meta charset="utf-8">

In like-dislike process, icons styling not working properly in PHP [closed]

I am working on a like-dislike process. I am using PHP for the backend. I have a table named comm_rating in my database.

(NOTE:- Suppose there are 2 users Alex and Siri.)

When Alex “likes” and Siri “dislikes” the post, then Siri see two “thumb-up” icons, and Alex see two “thumb-up” and two “thumb-down” icons, which is wrong.

For this, I want the suggestion what I am doing wrong.

The following codes are as follow-

$numSqlCommLike = "SELECT * FROM `comm_rating` WHERE `com_rat_blog_id`='40' AND `com_rat_com_id`='59' AND `com_rat_action`='like'";
$numResultLike = mysqli_query($conn, $numSqlCommLike);
$numRowsLike = mysqli_num_rows($numResultLike);
                                        
if ($numRowsLike>0) {
   echo '<button type="submit" class="like" name="button" value="like">';

   $likeSqlChangeColor = "SELECT * FROM `comm_rating` WHERE `com_rat_user_id`='31' AND `com_rat_blog_id`='40' AND `com_rat_com_id`='59' AND `com_rat_action`='like'";
   $likeResultChangeColor = mysqli_query($conn, $likeSqlChangeColor);
   $likeRowsChangeColor = mysqli_num_rows($likeResultChangeColor);

   if ($likeRowsChangeColor>0) {
      echo '<i class="fa-solid fa-thumbs-up"></i>';
   }else {
      echo '<i class="fa-regular fa-thumbs-up"></i>';
   }
                                                        
   echo '<p>'.$numRowsLike.'</p>
   </button>';

   $like_DislikeSqlChangeColor = "SELECT * FROM `comm_rating` WHERE `com_rat_user_id`='31' AND `com_rat_blog_id`='40' AND `com_rat_com_id`='59' AND `com_rat_action`='dislike'";
   $like_dislikeResultChangeColor = mysqli_query($conn, $like_DislikeSqlChangeColor);
   $like_dislikeRowsChangeColor = mysqli_num_rows($like_dislikeResultChangeColor);
   if ($like_dislikeRowsChangeColor>0) {
      echo '<button type="submit" class="dislike" name="button" value="dislike" style="display:none;"><i class="fa-regular fa-thumbs-down"></i><p>0</p></button>';
   }else {
      echo '<button type="submit" class="dislike" name="button" value="dislike" style="display:flex;"><i class="fa-regular fa-thumbs-down"></i><p>0</p></button>';
   }

}

// Number of comment dislikes
$numSqlCommDislike = "SELECT * FROM `comm_rating` WHERE `com_rat_blog_id`='40' AND `com_rat_com_id`='59' AND `com_rat_action`='dislike'";
$numResultDislike = mysqli_query($conn, $numSqlCommDislike);
$numRowsDislike = mysqli_num_rows($numResultDislike);
                                        
if ($numRowsDislike>0) {
    $dislike_LikeSqlChangeColor = "SELECT * FROM `comm_rating` WHERE `com_rat_user_id`='31' AND `com_rat_blog_id`='40' AND `com_rat_com_id`='59' AND `com_rat_action`='like'";
    $dislike_LikeResultChangeColor = mysqli_query($conn, $dislike_LikeSqlChangeColor);
    $dislike_LikeRowsChangeColor = mysqli_num_rows($dislike_LikeResultChangeColor);

    if ($dislike_LikeRowsChangeColor>0) {
        echo '<button type="submit" class="like" name="button" value="like" tyle="display:none;"><i class="fa-regular fa-thumbs-up"></i><p>0</p></button>';
    }else {
        echo '<button type="submit" class="like" name="button" value="like" tyle="display:flex;"><i class="fa-regular fa-thumbs-up"></i><p>0</p></button>';
    }

    echo '
    <button type="submit" class="dislike" name="button" value="dislike">';

    $dislikeSqlChangeColor = "SELECT * FROM `comm_rating` WHERE `com_rat_user_id`='31' AND `com_rat_blog_id`='40' AND `com_rat_com_id`='59' AND `com_rat_action`='dislike'";
    $dislikeResultChangeColor = mysqli_query($conn, $dislikeSqlChangeColor);
    $dislikeRowsChangeColor = mysqli_num_rows($dislikeResultChangeColor);

    if ($dislikeRowsChangeColor>0) {
       echo '<i class="fa-solid fa-thumbs-down"></i>';
    }else {
       echo '<i class="fa-regular fa-thumbs-down"></i>';
    }
    echo '<p>'.$numRowsDislike.'</p>
    </button>
    ';
}

if ($numRowsLike===0 && $numRowsDislike===0) {
   echo '
        <button type="submit" class="like" name="button" value="like"><i class="fa-regular fa-thumbs-up"></i><p>0</p></button>
        <button type="submit" class="dislike" name="button" value="dislike"><i class="fa-regular fa-thumbs-down"></i><p>0</p></button>
   ';
}

When Alex like-
when_Alex_like

when when Alex “like” and and Siri “dislike” in Alex id-
when Alex like and and Siri dislike @ Alex

when Alex “like” and Siri “dislike” in Siri id-
when Alex like and and rt dislike @ Siri

$_REQUEST[] or $_POST[] Undefined array key error [duplicate]

I have a PHP script that gets two parameters from an AJAX script on another page, but it gets an error on each $_REQUEST[], gets the same error if using $_POST[]

Undefined array key “visitor” in /home/tltl2347/public_html/pagevisited.php on line 7

Undefined array key “pagename” in /home/tltl2347/public_html/pagevisited.php on line 8

Here is the script

<?php

    date_default_timezone_set('Australia/Perth');
    $today = date('Y-m-d H:i:s');
    $logdata = "rn";

    $userAnswer = $_REQUEST['visitor'];
    $pageName = $_REQUEST['pagename'];
    $visitorip = $_SERVER['REMOTE_ADDR'];

    $visitor =  $userAnswer;
    $pagename = $pageName;
    $output = $today . "," . $visitor . "," . $pagename . "," . $visitorip . $logdata;

    if(($visitor !== 'JAMES BOND')) // Avoid registring myself
    {
       if($visitor !== "")
       {
         $file = fopen("pagevisit.csv","a");
         fwrite($file,$output);
         fclose($file);
       }
    }
?>

But the line:

$output = $today . "," . $visitor . "," . $pagename . "," . $visitorip . $logdata;

Is executed down correctly

Is there a way for me to hold on until $visitor and $pagename are taken?

Error when insert data with javascript form

I have an order creation form that allows me to enter information for several products to be linked to the order.
Each product can have production items, and I’d like to add the possibility of entering the number of products to be produced for each task.
The product and job parts of the form are dynamically generated by javascript.

The current problem is that my php file doesn’t handle the input corresponding to the quantity of products for the production tasks.

if i create an order with only 1 product, it correctly processes its production tasks and the quantity of each.
If I create an order with several products, the first one will be processed correctly, but for the subsequent products, the quantity of each task will not be retrieved and inserted.

Javascript product production posts form :

  function addProductField() {
    var productFields = document.getElementById("product_fields");
    var index = productFields.childElementCount + 1;

    fetch("production_posts.php").then(response => response.json()).then(data => {
      var productionPostsOptions = data.map(post => `
          <div class="form-check">
              <input class="form-check-input" type="checkbox" name="production_post_id_${index}[]" value="${post.id}" id="production_post_${post.id}_${index}">
              <label class="form-check-label" for="production_post_${post.id}_${index}">
                  ${post.name}
              </label>
          </div>
          <div class="mb-3">
              <label class="form-label" for="production_post_quantity_${post.id}_${index}">
                  Quantité totale pour ${post.name} du produit_${index}
                  production_post_quantity_${post.id}_${index}
                  production_post_quantity_${index}[]
              </label>
              <input type="number" class="form-control" name="production_post_quantity_${index}[]" id="production_post_quantity_${post.id}_${index}" placeholder="Quantité totale">
          </div>
      `).join("");
.....

php code for inserting products and their production tasks :

// Insérer les détails de produits dans la table order_product_details
    $product_count = count($_POST['product_name_']);
    for ($i = 0; $i < $product_count; $i++) {
        $product_name = $_POST['product_name_'][$i];
        $product_ref = $_POST['product_ref_'][$i];
        $product_attributes = $_POST['product_attributes_'][$i];
        $product_comment = $_POST['product_comment_'][$i];
        $product_rush = isset($_POST['product_rush_'][$i]) ? 1 : 0;
        $product_template = isset($_POST['product_template_'][$i]) ? 1 : 0;
        $product_production_days = (int)$_POST['product_production_days_'][$i];
        $product_production_days_rush = (int)$_POST['product_production_days_rush_'][$i];

        $product_custom_file_comment = $_POST['product_custom_file_comment_'][$i] ?? '';


        $stmt = $pdo->prepare("INSERT INTO products (name, product_ref, product_attributes, rush_option, template_option, production_day, production_day_rush, comment, product_state) 
        VALUES (:product_name, :product_ref, :product_attributes, :rush_option, :template_option, :production_day, :production_day_rush, :product_comment, 7)");
        $stmt->execute([
            ':product_name' => $product_name,
            ':product_ref' => $product_ref,
            ':product_attributes' => $product_attributes,
            ':product_comment' => $product_comment,
            ':rush_option' => $product_rush,
            ':template_option' => $product_template,
            ':production_day' => $product_production_days,
            ':production_day_rush' => $product_production_days_rush
        ]);
        $product_id = $pdo->lastInsertId();

        $stmt = $pdo->prepare("INSERT INTO order_products (order_id, product_id) VALUES (:order_id, :product_id)");
        $stmt->execute([
            ':order_id' => $order_id,
            ':product_id' => $product_id
        ]);

        $production_post_ids = $_POST['production_post_id_' . ($i + 1)] ?? [];
        $production_post_quantities = $_POST['production_post_quantity_' . ($i + 1)] ?? [];
    
        // Insérer les relations entre les produits et les étapes de production avec les quantités
        foreach ($production_post_ids as $index => $post_id) {
            $quantity = isset($production_post_quantities[$index]) ? (int)$production_post_quantities[$index] : 0;
    
            // Vérifier que les données sont valides
            if ($post_id && $quantity > 0) {
                $stmt = $pdo->prepare("
                    INSERT INTO product_production (product_id, production_post_id, production_post_state_id, total_quantity) 
                    VALUES (:product_id, :production_post_id, 1, :total_quantity)
                ");
                $stmt->execute([
                    ':product_id' => $product_id,
                    ':production_post_id' => $post_id,
                    ':total_quantity' => $quantity
                ]);
            }
        }
...

don’t hesitate to let me know if you’re missing any information or if there’s a problem with my code.

I tried changing the data insertion method and the form layout.
For each product, each production task must be inserted with the associated quantity entered in the total_quantity field of the product_production table.
Currently, if there are several products, this only works for the first product.

How do I write a menu using forms for each item that works across several directories?

I am using a header in my website that incorporates a menu that uses forms instead of href so that parameters can be passed. The problem is that when I go into another directory and click on one of the menu link, it tries to find that link in the directory that I am in and not in the root or another directory.

Here is the menu code using href in a directory

          <a href="../index.php" class="active">Home</a>  
          <a href="../membership/join.php"class="joinus">Join Us</a>  
          <a href="../publications/pubs.php?action1=about">About Us</a>

Here is the code in the homepage

          <a href="index.php" class="active">Home</a>  
          <a href="membership/join.php"class="joinus">Join Us</a>  
          <a href="publications/pubs.php?action1=about">About Us</a>

I am looking for a solution where a single menu can be used in the root and directories and sub-directories.