WordPress Gutenberg Custom Block the viewScript does not get loaded on the frontend when my block is inserted

I’ve created a new custom Gutenberg block using the following package: @wordpress/create-block. This bootstrapped a complete plugin for me where I only needed to edit files in order to get things working.

All of the editor code is working. It is a hero/visual block where a user can select images and a title for the slide. It’s also correctly rendering on the frontend with all the images + titles.

The next thing to do is create the javascript in order for the carousel functionality to work, however, my viewScript (set to "file:./view.js" is not being loaded on the frontend. With loaded, I mean it’s not in the HTML and not in the network tab.

This is my block.json inside of my build folder:

  "$schema": "https://schemas.wp.org/trunk/block.json",
  "apiVersion": 3,
  "name": "custom-block/hero",
  "version": "0.1.0",
  "title": "Hero",
  "category": "widgets",
  "icon": "smiley",
  "description": "Custom hero block",
  "attributes": {
    "images": {
      "type": "array",
      "source": "query",
      "default": [],
      "selector": "img",
      "query": {
        "url": {
          "type": "string",
          "source": "attribute",
          "attribute": "src"
        },
        "alt": {
          "type": "string",
          "source": "attribute",
          "attribute": "alt"
        },
        "caption": {
          "type": "string",
          "source": "attribute",
          "attribute": "data-caption"
        }
      }
    }
  },
  "supports": {
    "html": false
  },
  "textdomain": "hero",
  "editorScript": "file:./index.js",
  "editorStyle": "file:./index.css",
  "style": "file:./style-index.css",
  "viewScript": "file:./view.js",
  "viewStyle": "file:./view.css"
}

As you can see, I’ve set my viewScript to load a file called view.js. This is also present in the build folder of my plugin, as you can see right here in the actual repository

My entrypoint for the plugin, called hero.php, does not make use of the render_callback function, so I should not have to manually enqueue this script. It looks as follows:

/**
 * Plugin Name:       Hero
 * Description:       Custom hero block.
 * Requires at least: 6.1
 * Requires PHP:      7.0
 * Version:           0.1.0
 * Author:            Daniel
 * License:           GPL-2.0-or-later
 * License URI:       https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain:       hero
 *
 * @package CreateBlock
 */

if ( ! defined( 'ABSPATH' ) ) {
  exit; // Exit if accessed directly.
}

function create_block_hero_block_init() {
  register_block_type( __DIR__ . '/build' );
}

add_action( 'init', 'create_block_hero_block_init' );

As I mentioned, when I insert the block, save the page and go to the frontend I’m expecting this view.js file to be loaded, but it’s nowhere to be found. I’ve searched everywhere online, but for everybody else it seems to be working. Am I missing a crucial step?

Thank you in advance.

$cart = WC()->cart gives Uncaught Error: Call to a member function get_cart() on null

function tars_agg_part_load_charge() {
    
    include_once WC_ABSPATH . 'includes/wc-cart-functions.php';
    include_once WC_ABSPATH . 'includes/class-wc-cart.php';

    $cart = WC()->cart;
    
    if(empty($cart)){
        
        return true; //this is insane because the $cart object is populated but for some reason it thinks its null, so we're just returning true
    }

    if ( is_admin() && ! defined( 'DOING_AJAX' ) ) {
        return 'admin';
    }

    $part_load_tax = 0;

    foreach ( $cart->get_cart() as $cart_item ) {
        if ( tars_is_delivery( $cart_item['product_id'] ) && $cart_item['quantity'] < 16 ) {
            $charge = tars_get_part_load_charge( $cart_item['tars_delivery_data']['address_postcode'] );
            $data = $cart_item['data']->get_data();
            $product_name = $data['name'];
            $cart->add_fee( __('Part Load Charge '.$product_name, 'woocommerce'), intval($charge) );

            $part_load_tax = 57.6; // Set part load tax for applicable items
        }
    }

    foreach ( $cart->taxes as $tax_rate => &$tax ) {
        $tax += $part_load_tax; // Apply part load tax to existing taxes
    }

    return $part_load_tax;
}

I have an issue with my woocommerce cart. For some reason, $cart = WC()->cart; is apparently empty, but if I var_dump it, I get a massive object, so it’s not empty. I can’t run the rest of the code, because if I remove the if(empty($cart)){return true; } part of the code, then I get the error:

Uncaught Error: Call to a member function get_cart() on null...

So somehow $cart exists and doesn’t exist at the same time? Looking around, there was some advice about the cart only being initialised on the front end and I should include include_once WC_ABSPATH . 'includes/wc-cart-functions.php'; include_once WC_ABSPATH . 'includes/class-wc-cart.php', but this has not helped. How can Initialise and use the cart in my code? Hooks don’t work, as I need to return a variable.

Sort Multidimensional array column (PHP 8.2x) [duplicate]

How do I sort this array by “departureIcao”?
I have tried many, many ways using array_multisort() & array_column(). Just not getting the idea here. Please, any help?

Array
(
    [AAL1122] => Array
        (
            [callsign] => AAL1122
            [departureIcao] => SKBO
            [arrivalIcao] => KDFW
            [wakeClass] => M
            [onGround] => 
            [state] => En Route
            [flightRules] => I
        )

    [AAL190] => Array
        (
            [callsign] => AAL190
            [departureIcao] => KORD
            [arrivalIcao] => KJFK
            [wakeClass] => H
            [onGround] => 1
            [state] => Boarding
            [flightRules] => I
        )

    [AAL950] => Array
        (
            [callsign] => AAL950
            [departureIcao] => SBGR
            [arrivalIcao] => KJFK
            [wakeClass] => H
            [onGround] => 
            [state] => En Route
            [flightRules] => I
        )
)

My last 2 tries were:

$a = array_multisort(array_column($flights, 'departure_icao'), SORT_ASC, $flights);
$a = array_multisort(array_column($flights,'departure_icao'), $flights);

I have read (and tried) the several examples given in similar posts. Just keep getting errors.

Why aren’t query results retrieved when searching with Arabic letters in PHP and MySQL? [closed]

I have a PHP script that retrieves values from columns in the database. The script works well, but in some cases, it doesn’t retrieve values when searching for words containing the Arabic letter “إ” only. However, it retrieves all other words without any problem. I tried searching for this letter “إ” directly in the MySQL database, and it retrieved the values without any issues. But when using the query in PHP, it doesn’t retrieve anything when the word contains the letter “إ”. I need help solving this issue.

for($i = 0; $i < $total_rows; $i++) {
  // احصل على البيانات من كل صف ديناميكي
  $s_account = htmlspecialchars(strip_tags($antiXss->xss_clean($account[$i]))); 
  $s_debtor = filter_var($debtor[$i], FILTER_SANITIZE_NUMBER_INT); 
  $s_creditor = filter_var($creditor[$i], FILTER_SANITIZE_NUMBER_INT); 
  $s_description = htmlspecialchars(strip_tags($antiXss->xss_clean($description[$i]))); 

  // الإدراج في جدول entress_erp_part2
  $stmt2 = $con->prepare("INSERT INTO entress_erp_part2 (s_account, s_debtor, s_creditor, s_description,date, contact_id) VALUES (?, ?, ?, ?, ?,?)");
  $stmt2->bind_param("sssssi", $s_account, $s_debtor, $s_creditor, $s_description,$test_date, $last_id);
  $stmt2->execute();
  $stmt3=$con->prepare("SELECT * FROM categories WHERE acc_name = ? AND company=? ");
  $stmt3->bind_param("ss", $s_account,$company);
  $stmt3->execute();
  $result=$stmt3->get_result();
  echo $s_account.'-';
  foreach($result as $row){
  $balance=  $row['ac_balanced'];
  
   $newbalance = $balance + $s_debtor - $s_creditor;
   echo $newbalance;
  }
  $stmt4 =$con->prepare("UPDATE categories SET ac_balanced=? WHERE acc_name=? AND company=?");
  $stmt4->bind_param('iss', $newbalance, $s_account,$company);
  $stmt4->execute();
  var_dump($s_account, $s_debtor, $s_creditor, $s_description,$newbalance );
  // تم إدراج البيانات بنجاح، يمكنك هنا إظهار رسالة نجاح أو إجراء أي عمليات إضافية
}

The problem specifically lies in the following line: $stmt3=$con->prepare("SELECT * FROM categories WHERE acc_name = ? AND company=? "); and the variable $s_account when printed, its value appears correctly in all cases, but the values associated with it are not retrieved from the categories table when its value contains the Arabic letter “إ”.

Php if statement issue. Returning wrong result [duplicate]

I have this code that is returning incorrect value.
The result is ‘7 price3’ but it is wrong. 7 should fall on second if statement since $value is greater than 5 and less than or equal to 7. You can try on your php editor and it will return on the third if statement.

$price = 100;
$requestprice = 93;

$value = (($price - $requestprice) / $price) * 100;

if ($value <= 5) {
    echo $value . ' price 1';
} else if ($value > 5 && $value <= 7) {
    echo $value . ' price 2';
} else if ($value > 7 && $value <= 10) {
    echo $value . ' price 3';
}

Tried to run the code on any php editor and still got the wrong result

A text “d” suddenly started displaying across a website i am working on [closed]

After trying to increase my WordPress Memeory Limit in WP Config. I reloaded my site and started seeing the weird letter d displaying at the top of my website. All I pasted was this

define( 'WP_MEMORY_LIMIT', '256M' );

Here’s the site address here the site.

(Note: You might see it in maintenance mode, I just put up a page to show I am working on it, the website hasn’t been launched yet so no issues while it remains in maintenance mode)

I checked online and tried turning off error displays using the code below but still, it didn’t work. Please help me out. It displays across all pages of my website

ini_set('display_errors','Off');
ini_set('error_reporting', E_ALL );
define('WP_DEBUG', false);
define('WP_DEBUG_DISPLAY', false);

How can I use the WordPress Settings API to create a settings page for my plugin?

I am currently developing a WordPress plugin called FlexiPress. I’ve created a settings page in the WordPress dashboard where users can configure various features of the plugin.

I initially used a manual approach to create the form and manage the options, but I heard about the WordPress Settings API, which seems to be a cleaner and more secure way to manage plugin settings.

Could someone help me convert my current settings page using the WordPress Settings API? Indeed, I’ve read the WP doc but I still haven’t figured out how to use the Settings API for my plugin’s settings page. Here’s the code for that settings page:

<?php
// File : admin/general-settings.php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

// Include feature files
require_once(plugin_dir_path(__FILE__) . '/../includes/disable-automatic-updates-emails/disable-automatic-updates-emails.php');
require_once(plugin_dir_path(__FILE__) . '/../includes/disable-attachment-pages/disable-attachment-pages.php');
require_once(plugin_dir_path(__FILE__) . '/../includes/completely-disable-comments/completely-disable-comments.php');

// Checks if features are enabled
$disableautomaticupdatesemails_enabled = get_option('flexipress_general_enabled_disableautomaticupdatesemails', false);
$disableattachmentpages_enabled = get_option('flexipress_general_enabled_disableattachmentpages', false);
$completelydisablecomments_enabled = get_option('flexipress_general_enabled_completelydisablecomments', false);

// Form processing during submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['save_changes'])) {
    $disableautomaticupdatesemails_enabled = isset($_POST['disableautomaticupdatesemails_enabled']) && $_POST['disableautomaticupdatesemails_enabled'] === 'on';
    $disableattachmentpages_enabled = isset($_POST['disableattachmentpages_enabled']) && $_POST['disableattachmentpages_enabled'] === 'on';
    $completelydisablecomments_enabled = isset($_POST['completelydisablecomments_enabled']) && $_POST['completelydisablecomments_enabled'] === 'on';

    // Records toggle switch status
    update_option('flexipress_general_enabled_disableautomaticupdatesemails', $disableautomaticupdatesemails_enabled);
    update_option('flexipress_general_enabled_disableattachmentpages', $disableattachmentpages_enabled);
    update_option('flexipress_general_enabled_completelydisablecomments', $completelydisablecomments_enabled);
}


// Displays the form and switch toggles
?>
<div class="wrap" id="flexipress-plugin">
    <h2><?php esc_html_e('General Settings', 'flexipress'); ?></h2>

    <form method="post" action="">
        <?php
        // Features and their status
        $features = array(
            'disableautomaticupdatesemails' => __('Disable Automatic Updates Emails', 'flexipress'),
            'disableattachmentpages' => __('Disable Attachment Pages', 'flexipress'),
            'completelydisablecomments' => __('Completely Disable Comments', 'flexipress'),
            // Add other features as needed
        );

        foreach ($features as $key => $label) :
            $enabled = get_option("general_enabled_$key", false);
        ?>
            <div class="feature-toggle-pair">
                <label class="switch">
                    <input type="checkbox" name="<?php echo esc_js( $key ); ?>_enabled" <?php checked($enabled); ?>>
                    <span class="toggle-slider round"></span>
                </label>
                
                <div class="feature-details">
                    <h3><?php echo esc_html( $label ); ?></h3>
                    <?php if ($key === 'disableautomaticupdatesemails'): ?>
                        <p><?php esc_html_e('Stop getting emails about automatic updates on your WordPress site.', 'flexipress'); ?></p> <!-- Function description -->
                    <?php elseif ($key === 'disableattachmentpages'): ?>
                        <p><?php esc_html_e('Hide the Attachment/Attachments pages on the frontend from all visitors.', 'flexipress'); ?></p> <!-- Function description -->
                    <?php elseif ($key === 'completelydisablecomments'): ?>
                        <p><?php esc_html_e('Disable comments for all post types, in the admin and the frontend.', 'flexipress'); ?></p> <!-- Function description -->
                    <?php else: ?>
                        <p>.</p> <!-- Default description -->
                    <?php endif; ?>
                </div>

            </div>
        <?php endforeach; ?>

        <button type="submit" name="save_changes"><?php esc_html_e('Save Changes', 'flexipress'); ?></button>
    </form>
</div>

If anyone is familiar with the WordPress Settings API and can offer me some help, it would be extremely helpful and I would be very grateful.

Thank you very much for your help!
Alexis

My python script isn’t executed by PHP shell_exec()

I already seen issue talking about this on the platform but it didn’t resolve my problem.

I want to execute this python script :

import mysql.connector
import smtplib, ssl
from email.message import EmailMessage

def get_last_temperature():
    username = '***'
    passwd = '***'
    host = '127.0.0.1'
    db = 'temperature'
    sql_query = "SELECT * FROM temperature ORDER BY ID DESC LIMIT 1;"
    temp = 0

    # Connecto to database temperature
    conn = mysql.connector.connect(user=username, password=passwd, host=host, database=db)

    # execute sql query
    cursor = conn.cursor(dictionary=True)
    cursor.execute(sql_query)

    # get response
    result = cursor.fetchall()
    conn.close()
    size = len(result)

    temp = result[0]['temperature']

    return temp

def send_temperature(temp):
    subject = 'Temperature anomaly'
    body = 'Last temperature record is out of range : {}'.format(temp)
    sender = '***'
    receiver = "***"
    passwd = "***"

    msg = EmailMessage()
    msg['From'] = sender
    msg['To'] = receiver
    msg['Subject'] = subject
    msg.set_content(body)

    context = ssl.create_default_context()

    with smtplib.SMTP_SSL('smtp.gmail.com', 465, context=context) as server:
        server.login(sender, passwd)
        server.sendmail(sender, receiver, msg.as_string())

if __name__ == '__main__':
    try:
        print(ssl.OPENSSL_VERSION)
        temp = get_last_temperature()
        send_temperature(temp)
        print("Temperature sent by email.")
    except:
        print("Error")

From this PHP script :

if ($temperature < 7 || $temperature > 40)
{
    // $command = escapeshellcmd('touch /tmp/test.txt');
    // putenv('PYTHONPATH=/home/user/.local/lib/python3.8/site-packages/');
    $output = shell_exec('/usr/bin/python3 /home/user/Documents/Projet/send_temp/anomaly/main.py');
    echo "anomaly output : " . $output;
}

When i execute the python script manually it works.
I added www-data as the user of the python script and it doesn’t work.
As you can see i tried with simple command such as ‘touch /tmp/test.txt’ and it works.
Also when i execute a simple python script which create a tmp file it also work.

But with my script it doesn’t work. I also tried to add a different environment because it already solved some problems i had with mysql but it doesn’t work too and i don’t have any output.

I guess the problem is related to mysql or smtplib but i can’t find.

Can anyone give me some help ? 😉

WordPress .htaccess ignored from local apache server

I have a local WordPress setup where I want to develop plugins and themes. I’ve noticed that the url will include always index.php. I’ve tried to modify the permalink structure but nothing changed. At the moment my .htaccess file looks like this

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
RewriteBase /
RewriteRule ^index.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

I’ve installed recently a new version of php using MacPorts and I’m not sure if mod_rewrite is working correctly. How I can make things working correctly and have http://localhost:5000/pagename instead of http://localhost:5000/index.php/pagename?

How can i set my custom calculated price as actual sell price to basket in Woocommerce

Hello I am calculating price on the basis of total amount. I want to add after discount price as my sell price for product. so when i click on the add to cart button it should show the after discount price.

Here’s my html sturucture that i have created accoding to my requirenment:

<div class="woocommerce-variation-price">
    <span class="price-incvat" style="text-decoration:line-through;">
        <span class="woocommerce-Price-amount amount">
            <bdi>
                <span class="woocommerce-Price-currencySymbol">£</span>
                531.36
            </bdi>
        </span> 
            Inc. VAT
        </span><br>
        <span class="price2" style="text-decoration:line-through;">
            <span class="woocommerce-Price-amount amount">
                <bdi>
                    <span class="woocommerce-Price-currencySymbol">£</span>
                    442.80
                </bdi>
            </span> 
            Exc. VAT
        </span><br>
        <span class="price-incvat newprice">
            <span class="woocommerce-Price-amount amount">
                <bdi>
                    <span class="woocommerce-Price-currencySymbol">£</span>
                    478.22
                </bdi>
            </span> 
            Inc. VAT
        </span><br>
        <span class="price2 newprice">
            <span class="woocommerce-Price-amount amount">
                <bdi>
                    <span class="woocommerce-Price-currencySymbol">£</span>
                    398.52
                </bdi>
            </span>
            Exc. VAT
        </span>
    </div>

Here’s defalut html sturucture of Woocommerce

<div class="yith_wapo_group_total
        " data-product-price="442.8" data-product-id="205692">
<table>
<tbody><tr class="ywapo_tr_product_base_price">
<td data-nosnippet="">Product price</td>
<td data-nosnippet=""><div class="yith_wapo_group_product_price_total"><span class="price amount">£442.80</span></div></td>
</tr>
<tr class="ywapo_tr_additional_options">
<td data-nosnippet="">Additional options total:</td>
<td data-nosnippet=""><div class="yith_wapo_group_option_total"><span class="price amount">£0.00</span></div></td>
</tr>
<tr class="ywapo_tr_order_totals">
<td data-nosnippet="">Order total:</td>
<td data-nosnippet=""><div class="yith_wapo_group_final_total"><span class="price amount">£442.80</span></div></td>
</tr>
</tbody></table>
</div>

And here’s my Jquery code to calculate dicosunt price:

jQuery(function ($) {
$('.yith_wapo_group_final_total .price.amount').on("DOMSubtreeModified", function () {
var price_ele = jQuery(".woocommerce-variation.single_variation .woocommerce-variation-price");
var price_ele_simp = jQuery(".new-price-simple");
var add_price1 = jQuery(".yith_wapo_group_final_total .price.amount").text().replace(/£/g, "");
var add_price = add_price1.replace(/,/g, "");
var inc = (add_price * 20) / 100;
var inc_price = parseFloat(add_price) + parseFloat(inc);
if(bundleproduct != '')
{
var bundleExcVatFinalPrice = parseFloat(add_price) - (add_price * bundleproduct);
var bundleIncVatFinalPrice = parseFloat(bundleExcVatFinalPrice) + (bundleExcVatFinalPrice * 0.20);
if (add_price1 != 0 && price_ele.text() != "") 
   {
    price_ele.html('<span class="price-incvat" style="text-decoration:line-through;"><span           class="woocommerce-Price-amount amount"><bdi><span class="woocommerce-Price-currencySymbol">£</span>' + numberWithCommas(inc_price.toFixed(2)) + '</bdi></span> Inc. VAT</span></span><br><span class="price2" style="text-decoration:line-through;"><span class="woocommerce-Price-amount amount"><bdi><span class="woocommerce-Price-currencySymbol">£</span>' + numberWithCommas(add_price) + '</bdi></span> Exc. VAT</span><br><span class="price-incvat"><span class="woocommerce-Price-amount amount"><bdi><span class="woocommerce-Price-currencySymbol">£</span>' + numberWithCommas(bundleIncVatFinalPrice.toFixed(2)) + '</bdi></span> Inc. VAT</span></span><br><span class="price2"><span class="woocommerce-Price-amount amount"><bdi><span class="woocommerce-Price-currencySymbol">£</span>' + numberWithCommas(bundleExcVatFinalPrice.toFixed(2)) + '</bdi></span> Exc. VAT</span>');
   }
else if (price_ele.text() == "") 
   {
    price_ele.html('<span class="price-incvat" style="text-decoration:line-through;"><span class="woocommerce-Price-amount amount"><bdi><span class="woocommerce-Price-currencySymbol">£</span>' + numberWithCommas(inc_price.toFixed(2)) + '</bdi></span> Inc. VAT</span></span><br><span class="price2" style="text-decoration:line-through;"><span class="woocommerce-Price-amount amount"><bdi><span class="woocommerce-Price-currencySymbol">£</span>' + numberWithCommas(add_price) + '</bdi></span> Exc. VAT</span><br><span class="price-incvat"><span class="woocommerce-Price-amount amount"><bdi><span class="woocommerce-Price-currencySymbol">£</span>' + numberWithCommas(bundleIncVatFinalPrice.toFixed(2)) + '</bdi></span> Inc. VAT</span></span><br><span class="price2"><span class="woocommerce-Price-amount amount"><bdi><span class="woocommerce-Price-currencySymbol">£</span>' + numberWithCommas(bundleExcVatFinalPrice.toFixed(2)) + '</bdi></span> Exc. VAT</span>');
   }
}
}, 350);
});
});

Now What i want is.. when i click on add-to-cart button it should take span with class “price2 newprice” that is “398.52” in according to html given above.

Attched images for better understanding:
Before adding to cart

After clickeing basket button (It should show “398.52” price here

Thank You

I have tried this in above jquery i have prodvide:

$('.yith_wapo_group_total').attr('data-product-price', bundleExcVatFinalPrice);
$('.yith_wapo_group_final_total .price amount').attr('data-product-price', bundleExcVatFinalPrice);

But it’s not working. What i want is.. when i click on add-to-cart button it should take span with class “price2 newprice” that is “398.52” in according to html given above.

Call to a member function links() on array error with custom pagination in laravel 10

I’m trying to create a custom pagination in laravel 10, but I’m getting the error code

Call to a member function links() on array

this is my code:

CulinaryController.php

    public function index(Request $request)
    {
        $client = new Client();

        $qs = http_build_query($request->query());
        $qs = $qs ? '?'.$qs : '';
        $url = initURLPath("culinary" . $qs);
        $response = $client->get($url);
        // dd($response->getBody()->getContents());

        $json = json_decode((string)$response->getBody()->getContents(), true);
        
        if ($request->query('dd')) {
            // dd($response->getBody());
            dd($json);
        }

        $view_data = [
            'title' => 'Browse Culinary',
            'data' => $json,
        ];
        return view('culinary.index', $view_data);
    }

Api/V1/CulinaryController.php

    public function index(Request $request)
    {
        $perPage = $request->query('per_page', 8);
        $currentPage = $request->query('page', 1);
        $pageOffset = ($currentPage - 1) * $perPage;

        $result = Culinary::get();

        $data = $result->toArray();

        $resultWithPagination = new LengthAwarePaginator(
            array_slice($data, $pageOffset, $perPage),
            count($data),
            $perPage,
            LengthAwarePaginator::resolveCurrentPage(),
            [
                'path' => LengthAwarePaginator::resolveCurrentPath(),
                'query' => $request->query(),
            ]
        );

        return $resultWithPagination;
    }

and this is the code that causes the error in the blade view:

{{ $data->links() }}

any help is appreciated.

Why Django does not be deployed easily?

I have been learning Django for a long time, and I always find difficulties in deploying my projects,

I often deploy my projects on AWS, and it takes a lot of money,

also, the other platforms take a lot of fees to make your Django project deployed on their platforms,

After that I decided to move to PHP

here I found a difference,

and the difference is in the amount of time, that you need to deploy your project (which is a lot shorter than Django),

and the amount of fees that you need to pay to the platform to deploy your project on (it is 100%100 cheaper than Django),

and there are a lot of platforms for PHP, while Django there are few platforms to deploy your project on,

and PHP is much easier to deploy, there are platforms that just you take your project and drag it then drop it to them, and this is everything.

my questions are :

1- Why sometimes you have to take a cloud computer service then you have to install python , and everything in python , then you upload the Django project, it is like you are using it on your computer,

2- does Django need a whole computer system, to be deployed on because it does not work on a server directly ?

3- and why PHP is easier ? , is it because it works on a server directly and does not need anything like whole computer system to be deployed on , just it needs a server and that is is ?

4- and what is difference between hosting platforms, and services like cloud computer ?

Too few arguments to function AppJobsOrangeJob::__construct(), 0 passed in

when i run the laravel schedule comman, “php artisan schedule:work “i get this error. am running;
laravel 11
php 8.3


   ArgumentCountError 

  Too few arguments to function AppJobsOrangeJob::__construct(), 0 passed in D:projectspulseroutesconsole.php on line 8 and exactly 1 expected

  at appJobsOrangeJob.php:20
     16▕ {
     17▕     use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
     18▕     public $tries = 3;
     19▕     public  $orange;
  ➜  20▕     public function __construct( $orange )
     21▕     {
     22▕         $this->orange=$orange;
     23▕     }
     24▕

  1   routesconsole.php:8
      AppJobsOrangeJob::__construct()
  2   vendorlaravelframeworksrcIlluminateFoundationConsoleKernel.php:499

don’t know why i get that error.

here is my controller from where am dispatching the job

    public function index()
    {
        $oranges = DB::connection('connectpay')
            ->table('oranges')
            ->whereYear('created_at', '=', date('Y'))
            ->where('created_at', '<', Carbon::now()->subMinutes(1)->toDateTimeString())
            ->where('status', '=', 'pending')->get();

        foreach ($oranges as $orange) {
            OrangeJob::dispatch($orange);
        }
    }

my laravel’s job class

<?php

namespace AppJobs;

use AppModelsTest;
use CarbonCarbon;
use IlluminateBusQueueable;
use IlluminateContractsQueueShouldQueue;
use IlluminateFoundationBusDispatchable;
use IlluminateQueueInteractsWithQueue;
use IlluminateQueueSerializesModels;
use IlluminateSupportFacadesDB;
use function LaravelPromptstable;

class OrangeJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    public $tries = 3;
    public  $orange;
    public function __construct( $orange )
    {
        $this->orange=$orange;
    }

    public function handle():void
    {
    
       $orange= $this->orange;
        //        we check our transactions status
        $this->checkOrangeTransactions($orange);
    }

here is my routes/console file where i want to chedule the job

<?php

use AppJobsOrangeJob;



Schedule::job(new OrangeJob())->everySecond();

thank in advance

MongoError when uploading excel on Laravel platform

I have been having this error on Laravel 11 when I try to upload an Excel document where my database is a MongoDB instance:

Transaction numbers are only allowed on a replica set member or mongos

Steps to reproduce

  1. I installed Laravel 11
composer create-project laravel/laravel
  1. I added Laravel Mongodb composer package
composer require mongodb/laravel-mongodb
  1. I added the Laravel Excel composer package
composer require maatwebsite/excel:^3.1
  1. Added some User Interface to facilitate the upload of the document. I am trying to upload assets into the web platform.

  2. Created an AssetsImport document

php artisan make:import AssetsImport

The part that’s producing the error is on this file,

class AssetsImport implements ToCollection 
{
  public function collection(Collection $collection) 
  {
     foreach ($collection as $key => $row) {
        $asset = Asset::where('asset_no', $row[2])->first();
        if($asset) {
            continue;
        }
        // add the upload code
        ....
     }
  }
}

The above script is meant to check if there’s an existing Asset. If it’s there, then don’t add it (Continue with the foreach loop).

After checking this similar question, I still could not find a solution for this. Is this the correct way of implementing, and if so, how do I go about solving this error. I don’t have control over the database (there’s a Server Admin) so I cannot just add a replica set. Kindly assist.

Redmine – author_id Params Not Working When Creating New Issue Through REST API

I have migrated the Redmine version from 3.4.6 to 5.0.5 and I used to create a Redmine issue via the rest API, After migration author_id param is not working

I used the below code to create an issue

Before migration: It created an issue with dynamic author_id
After migration: It created an issue with the user’s ID that authenticates with the API. (author_id params not working)

<?php

// Redmine API endpoint for issues
$redmineUrl = 'https://live-url/issues.json';

$apiKey = 'XXXXXXXXXXXX';

// Issue data
$issueData = array(
    'issue' => array(
        'project_id' => 'xyz',
        'subject' => 'Issue subject',
        'description' => 'Issue description',
        'tracker_id' => 'bug', // Tracker ID for the type of issue (e.g., bug, feature, task)
        'status_id' => 'New', // Status ID for the initial status of the issue
        'author_id' => '12',
        'watcher_user_ids' => [70,16],   
    )
);

// Set up cURL
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $redmineUrl);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($issueData));
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    'X-Redmine-API-Key: ' . $apiKey
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

// Execute the request
$response = curl_exec($ch);

echo "<pre>";
print_r($response);

// Check for errors
if ($response === false) {
    echo 'Error: ' . curl_error($ch);
} else {
    echo 'Issue created successfully!';
}

// Close cURL
curl_close($ch);