Missing validation in Laravel in some cases when using Form Request

I have got a problem with Laravel.

I have created a custom Form Request – let’s call it CustomFormRequest. It is authorized and have got rules as it should be.

In one of the classes I use this request this way:

class CustomClass {

   public function __construct(CustomFormRequest $customFormRequest) {

      // Code only run from there after a successful validation.
      // If there was an error in validation then HTTP 422 error was send by Laravel

   }

}

From a Controller, usually I use this CustomClass in this way:

public function Custom(CustomClass $customClass) {

   // Code only run from there after a successful validation.

}

But, sometimes, I also try to access this class in this way from either a controller or from other class:

$customRequest = new CustomRequest();
$customRequest->sendMethod('POST');
$customRequest->request->add(...array of data...);
new CustomClass($customRequest);

But it turned out when I use the class this way Laravel somehow skips the validation and even when I gave an invalid data for the class, it will run and tries to put those invalid data into the database!

Is there anything that I missing!? Is another line needed to enforcing the validation!?

Thanks for any further help!

I also tried using $request->validate($request->rules()) but it leads to ERR_TOO_MANY_REDIRECTS.

Microsoft Ads OAuth Redirect Fails – Domain Not Recognized

I’d be incredibly grateful for your help. I work for a small company, and we run ads on Bing. I need to develop an API to integrate with the Microsoft Ads platform to retrieve spending reports and other data.

I came across this Laravel library that supports Facebook and Google ads: Laravel Ads SDK. Unfortunately, it doesn’t work with Bing Ads. The problem occurs when trying to retrieve the token; the redirect URL is:

https://login.microsoftonline.com/common/oauth2/v2.0/authorize?scope=https://ads.microsoft.com%2Fmsads.manage+offline_access&client_id=f43443-0808-7hg9-a9a9-934gb06914b0&response_type=code&redirect_uri=https%3A%2F%2Flogin.microsoftonline.com%2Fcommon%2Foauth2%2Fnativeclient&state=46891992

When I attempt to log in using the same email linked to our Bing Ads campaign or even a Hotmail account, I receive the error message: “Domain isn’t in our system. Make sure you typed it correctly.”

Has anyone encountered this issue or found a solution? Any advice would be much appreciated!

enter image description here

Do I need to have Microsoft account or an paid azure subscription or what? I have been on this seen 10th December and not got anywhere with it. Any help will go a long way. Thank you

P.S. We have tried using javascript and always experience the same blocked that the domain isn’t in our system. Make sure you typed it correctly

For gmail emails, SMTP email validations is not working properly

I’ve created an API which will take first name, last name and email and generate all possible combinations of emails and returns the valid emails(Which are exist in this world). It works for innofied.com but doesn’t works gmail.com. For gmail.com it says all the valid emails. I’m using gmail SMTP for this

The following is the code in api.php

Route::post('/validate-emails', [EmailValidationController::class, 'validateEmails']);

The following is the code in EmailValidationController

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;
use IlluminateSupportFacadesValidator;
use AppServicesIntegrationsEmailEmailServiceInterface;

class EmailValidationController extends Controller
{
    public function __construct(
        private EmailServiceInterface $emailValidationService
    ) {}

    public function validateEmails(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'first_name' => 'required|string',
            'last_name' => 'required|string',
            'domain' => 'required|string'
        ]);

        if ($validator->fails()) {
            return response()->json(['error' => $validator->errors()], 422);
        }

        $first = strtolower($request->first_name);
        $last = strtolower($request->last_name);
        $domain = strtolower($request->domain);

        $emails = $this->emailValidationService->generateEmailPermutations($first, $last, $domain);
        $validEmails = $this->emailValidationService->validateEmails($emails);

        return response()->json([
            'all_combinations' => $emails,
            'valid_combinations' => array_values($validEmails),
        ]);
    }
}

The following is the code EmailService

<?php

namespace AppServicesIntegrationsEmail;

use AppServicesIntegrationsEmailEmailServiceInterface;
use IlluminateSupportFacadesLog;

class EmailService implements EmailServiceInterface
{
    /**
     * Generate all possible email permutations.
     *
     * @param string $firstName
     * @param string $lastName
     * @param string $domain
     * @return array
     */
    public function generateEmailPermutations(
        string $firstName,
        string $lastName,
        string $domain
    ): array {
        $first = strtolower($firstName);
        $last = strtolower($lastName);
        $f = substr($first, 0, 1);
        $l = substr($last, 0, 1);

        return [
            "$first@$domain",
            "$last@$domain",
            "$first$last@$domain",
            "$first.$last@$domain",
            "$f$last@$domain",
            "$f.$last@$domain",
            "$first$l@$domain",
            "$first.$l@$domain",
            "$f$l@$domain",
            "$f.$l@$domain",
            "$last$first@$domain",
            "$last.$first@$domain",
            "$last$f@$domain",
            "$last.$f@$domain",
            "$l$first@$domain",
            "$l.$first@$domain",
            "$l$f@$domain",
            "$l.$f@$domain",
            "$first-$last@$domain",
            "$f-$last@$domain",
            "$first-$l@$domain",
            "$f-$l@$domain",
            "$last-$first@$domain",
            "$last-$f@$domain",
            "$l-$first@$domain",
            "$l-$f@$domain",
            "{$first}_{$last}@$domain",
            "{$f}_{$last}@$domain",
            "{$first}_{$l}@$domain",
            "{$f}_{$l}@$domain",
            "{$last}_{$first}@$domain",
            "{$last}_{$f}@$domain",
            "{$l}_{$first}@$domain",
            "{$l}_{$f}@$domain",
        ];
    }

    /**
     * Validate email addresses using MX and SMTP verification.
     */
    public function validateEmails(array $emails): array
    {
        return array_filter($emails, fn($email) => $this->validateEmailSMTP($email));
    }

    private function getMXRecord($domain)
    {
        $mxRecords = dns_get_record($domain, DNS_MX);
        return $mxRecords ? $mxRecords[0]['target'] : null;
    }

    private function validateEmailSMTP($email)
    {
        $domain = explode('@', $email)[1];
        $mxServer = $this->getMXRecord($domain);

        if (!$mxServer) {
            return false; // No mail server found
        }

        $from = config('mail.from.address');
        $mailServerDomain = config('mail.mailers.smtp.mail_server_domain');
        $sock = fsockopen($mxServer, 25, $errno, $errstr, 5);

        if (!$sock) {
            return false;
        }

        stream_set_timeout($sock, 5);

        $this->getSMTPResponse($sock); // Read initial 220 response
        fwrite($sock, "HELO $mailServerDomainrn");
        $this->getSMTPResponse($sock); // Read HELO response

        fwrite($sock, "MAIL FROM:<$from>rn");
        $this->getSMTPResponse($sock); // Read MAIL FROM response

        fwrite($sock, "RCPT TO:<$email>rn");
        $response = $this->getSMTPResponse($sock); // Read RCPT TO response

        fwrite($sock, "QUITrn");
        fclose($sock);

        return strpos($response, "250") !== false && !strpos($response, "550");
    }

    private function getSMTPResponse($sock)
    {
        $response = '';
        while ($line = fgets($sock, 1024)) {
            $response .= $line;
            if (substr($line, 3, 1) == " ") { // End of response
                break;
            }
        }
        return $response;
    }
}

It works for the following input
Input

{
    "first_name": "deep",
    "last_name": "jajodia",
    "domain": "innofied.com"
}

Output

{
    "all_combinations": [
        "[email protected]",
        "[email protected]",
        "[email protected]",
        "[email protected]",
        "[email protected]",
        "[email protected]",
        "[email protected]",
        "[email protected]",
        "[email protected]",
        "[email protected]",
        "[email protected]",
        "[email protected]",
        "[email protected]",
        "[email protected]",
        "[email protected]",
        "[email protected]",
        "[email protected]",
        "[email protected]",
        "[email protected]",
        "[email protected]",
        "[email protected]",
        "[email protected]",
        "[email protected]",
        "[email protected]",
        "[email protected]",
        "[email protected]",
        "[email protected]",
        "[email protected]",
        "[email protected]",
        "[email protected]",
        "[email protected]",
        "[email protected]",
        "[email protected]",
        "[email protected]"
    ],
    "valid_combinations": [
        "[email protected]",
        "[email protected]"
    ]
}

Here [email protected],[email protected] are valid and exist. It works for innofied.com but for gmail it doesn’t work

Input for gmail

{
    "first_name": "sourav",
    "last_name": "saha964",
    "domain": "gmail.com"
}

Output

{
    "all_combinations": [
        "[email protected]",
        "[email protected]",
        "[email protected]",
        "[email protected]",
        "[email protected]",
        "[email protected]",
        "[email protected]",
        "[email protected]",
        "[email protected]",
        "[email protected]",
        "[email protected]",
        "[email protected]",
        "[email protected]",
        "[email protected]",
        "[email protected]",
        "[email protected]",
        "[email protected]",
        "[email protected]",
        "[email protected]",
        "[email protected]",
        "[email protected]",
        "[email protected]",
        "[email protected]",
        "[email protected]",
        "[email protected]",
        "[email protected]",
        "[email protected]",
        "[email protected]",
        "[email protected]",
        "[email protected]",
        "[email protected]",
        "[email protected]",
        "[email protected]",
        "[email protected]"
    ],
    "valid_combinations": [
        "[email protected]",
        "[email protected]",
        "[email protected]",
        "[email protected]",
        "[email protected]",
        "[email protected]",
        "[email protected]",
        "[email protected]",
        "[email protected]",
        "[email protected]"
    ]
}

Here only [email protected] is valid and others are not

why can’t the relation manager from the address appear when creating an order

why can’t the relation manager from the address appear when creating an order but when editing and viewing it appears

 public static function getRelations(): array
    {
        return [
            AddressRelationManager::class,
        ];
    }

I have already had
relations in model orders

 public function address()
    {
        return $this->hasOne(Address::class);
    }

Why is it still not showing up when placing an order?

How to add a custom tab in the main course navigation bar, not in the “More” menu?

I am developing a block plugin for Moodle, and I want to add a custom tab to the main course navigation bar (directly visible, not hidden under the “More” menu). Currently, my code adds the tab to the “More” menu. Here’s what I have so far:

$context = context_course::instance($COURSE->id);
$coursenode = $PAGE->settingsnav->find('courseadmin', navigation_node::TYPE_COURSE);

if ($coursenode) {
    $node = navigation_node::create(
        get_string('myblock', 'block_myblock'),
        new moodle_url('/blocks/myblock/view.php', ['courseid' => $COURSE->id]),
        navigation_node::TYPE_SETTING,
        null,
        'customnode',
        new pix_icon('i/settings', '')
    );

    $node->showinflatnavigation = true;
    $node->forceintomoremenu = false;
    $node->showinsecondarynavigation = true;
    $node->display = true;

    $coursenode->add_node($node, 'filtermanagement');
    $node->make_active();
    $node->force_open();
}

The tab is currently added under the “More” menu instead of being directly visible in the course navigation bar.

How can I ensure that my custom tab appears directly in the main course navigation bar and not under “More”?

PHP Mailer Emails with the same sender, recipient and subject dont go into one email thread [duplicate]

Please image below. The sender is the same subject is the same email address of the sender is the same but they always go into separate email and not in one email thread as it should.

Below is my PHP mailer script.

use PHPMailerPHPMailerPHPMailer;
use PHPMailerPHPMailerSMTP;
use PHPMailerPHPMailerException;

//Load Composer's autoloader
require 'vendor/autoload.php';


function send_mail($to,$subject,$body,$from = '', $host = "[email protected]"){
  //Create an instance; passing `true` enables exceptions
 $mail = new PHPMailer(true);

 try {
    //Server settings
//    $mail->SMTPDebug = SMTP::DEBUG_SERVER;                      //Enable verbose debug output
    $mail->isSMTP();                                            //Send using SMTP
    $mail->Host       = 'mail.privateemail.com';   //Set the SMTP server to send through
    $mail->SMTPAuth   = true;                                   //Enable SMTP authentication
    $mail->Username   = '[email protected]';                     //SMTP username
    $mail->Password   = 'xxxxx';          //SMTP password
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS;            //Enable implicit TLS encryption
    $mail->Port       = 465;                                    //TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS`

    //Recipients
    $mail->setFrom($host, $from);
   // $mail->addAddress($to, 'Subscriber');     //Add a recipient
    $mail->addAddress($to);               //Name is optional
   // $mail->addReplyTo('[email protected]', 'Sensored Support');
    //$mail->addCC('[email protected]');
    $mail->addBCC('[email protected]');

    //Attachments
   // $mail->addAttachment('/var/tmp/file.tar.gz');         //Add attachments
   // $mail->addAttachment('/tmp/image.jpg', 'new.jpg');    //Optional name

    //Content
    $mail->isHTML(true);                                  //Set email format to HTML
    $mail->Subject = $subject;
    $mail->Body    = $body;
    //$mail->AltBody = ' ';

    $mail->send();
    echo 'Message has been sent';
 } catch (Exception $e) {
    echo "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
 }
}

enter image description here

Hide a menu item if user has posted a specific post_type

I’m trying to create a code snippet that will allow me to hide a menu item if a user has already posted at least 1 of a specific post type. I have this:

function hide_specific_menu_item($items, $args) {
    $user_id = get_current_user_id(); //get the user_id
    $post_type = "student"; // define the post type
    $posts = count_user_posts( $user_id, $post_type ); //count user's posts
    
    if($posts > 0){
        foreach ($items as $key => $item) {
            if ($item->title === 'Add Student') { //hide the menu item
                unset($items[$key]);
            }
        }
    }
    
    return $items;
}

add_filter('wp_nav_menu_objects', 'hide_specific_menu_item', 10, 2);

But the above isn’t working.

I would greatly appreciate it if someone could help me figure out where I’m going wrong.

Why does PHP-FPM queue connections when max active processes is less than total processes

My team is using PHP-FPM, configured statically with a max of 32 processes, in a Kubernetes cluster. We’re autoscaling based on PHP-FPM metrics, and there are many replicas. I’m frequently (i.e. on all replicas) seeing the PHP-FPM status show queued connections, even though the max active processes is below total processes. For example:

pool:                 www
process manager:      static
start time:           06/Feb/2025:17:37:07 +0000
start since:          80556
accepted conn:        265772
listen queue:         0
max listen queue:     2
listen queue len:     511
idle processes:       27
active processes:     5
total processes:      32
max active processes: 21
max children reached: 0
slow requests:        0

Note that the max active processes is 21 of the 32 available, but that the listen queue has reached 2. Why are connections being queued when there are idle processes?

soon as I click on a color variation on the product archive page, the option of the quantity button and the add to cart button will open for me?

I have a code that works but does not give me the option that once I select a color variation to also see the product image by color
this is the code:

add_filter( 'woocommerce_loop_add_to_cart_link', function( $html, $product ) {
    if ( $product && $product->is_type( 'simple' ) && $product->is_purchasable() && $product->is_in_stock() && ! $product->is_sold_individually() ) {
        $html = '<form action="' . esc_url( $product->add_to_cart_url() ) . '" class="wcb2b-quantity" method="post" enctype="multipart/form-data">';
        $html .= woocommerce_quantity_input( array(), $product, false );
        $html .= '<button type="submit" class="button alt">' . esc_html( $product->add_to_cart_text() ) . '</button>';
        $html .= '</form>';
    }
    return $html;
}, 10, 2 );

add_action( 'woocommerce_before_shop_loop', 'show_production_variations_on_shop_page' );
function show_production_variations_on_shop_page() {
    remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart', 10 );
    add_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_single_add_to_cart', 30 );
}

I would like someone to help with the code so that I can click on color variation and the image on the product will change to the color that was clicked

Access Private Resource File

I am trying to read the mask.json from a site_package and use that to generate an api response using an extension like nnrestapi

this is the code i currently have

$filePath = "EXT:site_package/Configuration/Mask/mask.json";
$resourceFactory = GeneralUtility::makeInstance(ResourceFactory::class);
$file = $resourceFactory->retrieveFileOrFolderObject($filePath);
$fileContent = $file->getContents();
// do something with $fileContent

but I am getting this error

Tried to access a private resource file "EXT:site_package/Configuration/Mask/mask.json" from fallback compatibility storage. This storage only handles public files.

How can I access that file? Is there a better way? Maybe to edit the site_package directly?

Xero api connection

I’ve been over and over the docs and posts and I’m obviously missing something.
Can anyone explain or point me to a clear example of how I can connect to the xero api using my client_id and secret and NOT requiring a click to authorise the connection ?

I’m trying to automatically generate invoices and send them to bookings on a public site and I can’t see how the redirect and manual authorisation could work in this scenario.

I’m using the xero-php-oauth2 library but all examples seem to require a user to manually authorize access or they assume a token exists as per in the documentation example below.
I have found information on creating an invoice and adding lineitems but just can’t seem to get my head around how to automate the process of connecting

What am I missing ??

require_once(__DIR__ . '/vendor/autoload.php');

// Configure OAuth2 access token for authorization: OAuth2
$config = XeroAPIXeroPHPConfiguration::getDefaultConfiguration()->setAccessToken( 'YOUR_ACCESS_TOKEN' );       

$apiInstance = new XeroAPIXeroPHPApiAccountingApi(
    new GuzzleHttpClient(),
    $config
);``` 
 

How to use New Line command in API calling? [closed]

New Line Command is not working properly when I called client API.

$text=nl2br("Which desert is located in Qatar? n A)Kalahari Desert n B)Gobi Desert n 
C)Rub'al Khali (Empty Quarter) n D)Sahara Desert. n Please reply A/B/C/D.");   
            

$jsonData = array(
    'text' =>  $text,
    'msisdn' => $msisdn                     
);

I tried to use n in $text variable & result as below

enter image description here

How to remove <br / > from the SMS text?

but it works when I called API from Postman as below.

enter image description here

OUTPUT

enter image description here

How can I create a custom Moodle plugin that integrates with an external API?

I am developing a custom Moodle plugin that needs to fetch data from an external API and display it in a course module. My goal is to:

  1. Authenticate with the external API using OAuth2.
  2. Fetch specific data (e.g., user progress, grades, or content).
  3. Display this data in a custom Moodle block or activity module.

I’ve reviewed the Moodle Developer Documentation, but I’m unclear on:

  • How to structure the plugin for external API integration.
  • Where to implement API calls (e.g., lib.php, custom classes, or AJAX).
  • The best practices for securely storing and refreshing OAuth2 tokens.

Here’s what I’ve tried so far:

  • I’ve created the basic plugin structure using the Moodle plugin skeleton generator.
  • I’ve registered an external service for the API under Site Administration > Plugins > Web Services.

However, I’m struggling with how to handle authentication and integrate API data seamlessly into Moodle.

What are the best practices for implementing such functionality in Moodle plugins? Are there any existing examples or patterns I should follow?