how to add code to service provider by artisan command

i created an Artisan Command that created Repository. A Repository File and an Interface.
when user run below command, this files will be generated.

php artisan make:repository RepositoryName

now, next step is to add bind code to RepositoryServiceProvider in register method.
How do I add the following code to that file?

$this->app->bind(
    RepositoryNameInterface::class,
    RepositoryName::class,
);

and generally, how to add custom code to the method of class in PHP?

Is there a way to pass a variable into an if statement of an Ajax request?

I am using Yajra Datatables to display audit data into a table. I have a function which gets audit data from a table using a received ID of a user and Request and gets the data using that ID. When i check if the request is Ajax using an if statement; I cannot get any variable outside of this if statement and even if i hard code a variable into this if statement so it should get the data based on this variable nothing is happening. I even tried die and dump the hard coded variable but its not dumping it on the screen. Below is the function;

    public function getByUser(User $user, Request $request)
{
    
    $email = $user->email;

       if ($request->ajax()) {
        //$email = "[email protected]";
        $audits = Audit::where('action_taken_by', $email)
        ->orderBy('id', 'DESC')
        ->get();

            return Datatables::of($audits)
                    ->addIndexColumn()
                    ->rawColumns(['action'])
                    ->make(true);
        }

    return view('audit/index');
}

If i remove the if statement the code is working but just dumping the array on the screen and not returning them on the view as intended and if the if statement is there all the results are displayed without checking the email variable. Is there a way i can pass this variable into the if statement?

Symfony 5 – A problem with the form to registrate a credit card with MangoPay

I’m trying to register a credit card with MangoPay.

I’ve installed the mangopay/php-sdk-v2 package.

To register a credit card, it needs three steps.

  1. Create a token of the card
  2. Post card info (using a url created by the token) that will render a string that start with data=
  3. Add the registered card to the MangoPay user
// ProfilController.php 

   /**
     * @Route("/payment/{id}", name="payment")
     * * @param int $id
     */
    public function payment(Request $request, ApiUser $ApiUser, $id): Response
    {           
            $returnUrl = "";

            $user = $this->userRepository->findOneBy(['id' => $id]);
            $userId = $user->getIdMangopay();
            $registration = $ApiUser->Registration($userId);
            
            if($request->request->count() > 0){
                $payment = new PaymentMethod(); 
                $payment->setName($request->request->get('name'));
                $payment->setCardNumber($request->request->get('cardNumber'));
        
                $entityManager = $this->getDoctrine()->getManager();
                $entityManager->persist($payment);
                $entityManager->flush();

                $registrationCard = $ApiUser->RegistrationCard($registration, $request);

                $returnUrl = 'http' . (isset($_SERVER['HTTPS']) ? 's' : '') . '://' . $_SERVER['HTTP_HOST'];
                $returnUrl .= '/profil';
            }
            
            return $this->render('home/payment.html.twig', [
                    'CardRegistrationUrl' => $registration->CardRegistrationURL,
                    'Data' => $registration->PreregistrationData,
                    'AccessKeyRef' => $registration->AccessKey,
                    'returnUrl' => $returnUrl,
            ]);
    }

The Registration and ResitrationCard functions come from the ApiUser file:

// ApiUser.php

    public function Registration($UserId)
    {
        $CardRegistration = new MangoPayCardRegistration();
        $CardRegistration->UserId = $UserId;
        $CardRegistration->Currency = "EUR";
        $CardRegistration->CardType = "CB_VISA_MASTERCARD";
        $Result = $this->mangoPayApi->CardRegistrations->Create($CardRegistration);
      $this->registrationInfo = $Result;
      $this->CardRegistrationUrl = $Result->CardRegistrationURL;

      return $Result;
    }

    public function RegistrationCard($CardInfo)
    {
      $cardRegister = $this->mangoPayApi->CardRegistrations->Get($CardInfo->Id);

      $cardRegister->RegistrationData = $_SERVER['QUERY'];
      
      $updatedCardRegister  = $this->mangoPayApi->CardRegistrations->Update($cardRegister);
    
      return $Result;
    }

I’m able to create the token of the card and get the data= string, but the problem is that I cannot do the last step.

It seems that I cannot enter into the if statement, so it doesn’t register the card on the database and I cannot update the card information (3rd step).

The returnUrl, I can simply put it outside of the if statement to make it works, but I want to change it only if the form is valid.

How can I fix the statement? Why doesn’t it enter into the if?

Configure CLI interpreter for PHPStorm on Mac

I have installed PHP from brew and it works just fine in VS Code, but on PHPStorm I am not able to configure the interpreter in order to debug my php code.

When executing:

php -v 

on terminal, I get:

PHP 8.0.17 (cli) (built: Apr 5 2022 22:43:04) ( NTS ) Copyright (c)
The PHP Group Zend Engine v4.0.17, Copyright (c) Zend Technologies
with Zend OPcache v8.0.17, Copyright (c), by Zend Technologies

which tells me that this installed correctly.

Move uplaod file false result? [closed]

I try to accept a file using php:

<?php

if (isset($_FILES["file"])) {

  $uploaddir = '/';
  $uploadfile = $uploaddir . basename($_FILES['file']['name']);


  if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile)) {
    echo "File is valid, and was successfully uploaded.n";
  } else {
    echo "Error";
  }
}

I send Postman request as POST form-data: file: Filename.

Why I always get echo "Error";?

how to print values using only one array values inside MYSQL (IN) operator?

I have a database named (myDatabase) and a table inside which is called Category, inside the table I have 3 columns (ids, categories, product_name), I want to retrieve the values or rows that contains specific categories, or let’s say fetching values inside the table depending on an array containing some categories available in the table. This is my code but it gives error, it is not working when I want to print them.

$conn = mysqli_connect('localhost','root','','myDatabase');

$MyCategories = array('food','entertaintment','vehicle');
$where_in = implode(',', $MyCategories);

$query = "SELECT * FROM Category WHERE categories IN ($MyCategories);";

$result = mysqli_query($conn,$query);

$cats = mysqli_fetch_all($result,MYSQLI_ASSOC);

print_r($cats);

I tried that with mysqli_fetch_array() but it doesn’t work, says (arrays to string conversion) error.

$conn = mysqli_connect('localhost', 'root', '', 'myDatabase');

$MyCategories = array('food', 'entertaintment', 'vehicle');
$where_in = implode(',', $MyCategories);

$query = "SELECT * FROM Category WHERE categories IN ($MyCategories);";

$result = mysqli_query($conn, $query);

while ($row = mysqli_fetch_array($result)) {
echo $row['2'];
// third column (product_name) in table Category
}

please help me, thanks a bunch.

Does Magento 2 Cart Price Rule’s Applicability Check Works Fine?

Lately, I am trying to tweak Magento 2 Cart Price Rule feature for our business requirements and I realized something. First of all, I need to say that we override MagentoSalesRuleModelRuleConditionProductSubselect::loadAttributeOptions() because in our location we must apply the discount on top of the tax included amount so we changed the ‘base_row_total’ with the ‘base_row_total_incl_tax’. Here is the scenario;

I have 2 Cart Price Rule;(₺ = currency)

  1. 50% discount for items in the cart, with cart condition; amount > 250₺, priority 0
  2. 20% discount for items in the cart, with cart condition; amount > 200₺, priority 1

I have a cart with 1 item with a total of 300₺ and let’s say that shipping is free. Our requirements say that; it should apply the first cart price rule and should not apply the second cart price rule because after applying the first cart price rule cart total is going down to 150₺ thus second cart price rule’s condition is not met from now on.

If we go back to the reality Magento validates conditions by the product’s attributes; Magento always looks for the same value, not the discounted fresh value.
MagentoSalesRuleModelRuleConditionProduct::validate($model) declares that;

$total += ($hasValidChild && $useChildrenTotal) ?
 $childrenAttrTotal * $item->getQty() : $item->getData($attr);
// $attr value is "base_row_total_incl_tax" for our case, and it does not change after every rule process step

return $this->validateAttribute($total); // this func just makes a logical comparison with boolean return

So, what do you think about this topic? Has anyone thought about it, should I just change the $total with the latest discount applied cart amount(using registry) or does anyone have a better idea?

Laravel Migrating a migration I didn’t make

I made 4 migrations and I’m trying to migrate them with php artisan migrate:fresh. However, I’m getting an error

Migrating: 2019_12_14_000001_create_personal_access_tokens_table

SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 1000 bytes (SQL: alter table `personal_access_tokens` add index `personal_access_tokens_tokenable_type_tokenable_id_index`(`tokenable_type`, `tokenable_id`))

  at C:UsersVictorDesktopOefenexamenoefenexamenvendorlaravelframeworksrcIlluminateDatabaseConnection.php:745
    741▕         // If an exception occurs when attempting to run a query, we'll format the error
    742▕         // message to include the bindings with SQL, which will make this exception a
    743▕         // lot more helpful to the developer instead of just the database's errors.
    744▕         catch (Exception $e) {
  ➜ 745▕             throw new QueryException(
    746▕                 $query, $this->prepareBindings($bindings), $e
    747▕             );
    748▕         }
    749▕     }

  1   C:UsersVictorDesktopOefenexamenoefenexamenvendorlaravelframeworksrcIlluminateDatabaseConnection.php:530
      PDOException::("SQLSTATE[42000]: Syntax error or access violation: 1071 Specified key was too long; max key length is 1000 bytes")

  2   C:UsersVictorDesktopOefenexamenoefenexamenvendorlaravelframeworksrcIlluminateDatabaseConnection.php:530
      PDOStatement::execute()

However, I don’t have the 2019_12_14_000001_create_personal_access_tokens_table migration, why is it being ran?

Cannot use import statement outside a module in laravel project

I’m writing a web cryptocurrency web service and trying to encode smart contract parameters with the Etherium js library. I have created a js file and trying to import ethers library that I have installed. When I’m trying to call the created js function I get an error Uncaught SyntaxError: Cannot use import statement outside a module (at encoder.js:4:1) Here is the code

import { ethers } from "ethers";

const AbiCoder = ethers.utils.AbiCoder;
const ADDRESS_PREFIX_REGEX = /^(41)/;
const ADDRESS_PREFIX = "41";

async function encodeParams(inputs) {
    let typesValues = inputs;
    let parameters = "";

    if (typesValues.length == 0) return parameters;
    const abiCoder = new AbiCoder();
    let types = [];
    const values = [];

    for (let i = 0; i < typesValues.length; i++) {
        let { type, value } = typesValues[i];
        if (type == "address")
            value = value.replace(ADDRESS_PREFIX_REGEX, "0x");
        else if (type == "address[]")
            value = value.map((v) =>
                toHex(v).replace(ADDRESS_PREFIX_REGEX, "0x")
            );
        types.push(type);
        values.push(value);
    }

    console.log(types, values);
    try {
        parameters = abiCoder.encode(types, values).replace(/^(0x)/, "");
    } catch (ex) {
        console.log(ex);
    }
    return parameters;
}

async function main() {
    let inputs = [
        {
            type: "address",
            value: "412ed5dd8a98aea00ae32517742ea5289761b2710e",
        },
        { type: "uint256", value: 50000000000 },
    ];
    let parameters = await encodeParams(inputs);
    console.log(parameters);

    main();
}

Please can someone help me to understand the issue? I’m using Laravel framework. If any additional info is needed I will be happy to provide it.

Execute command on phpunit test

I’m writing a functional test, the execution of tested code includes the execution of a symfony command but it seems like the command its not executes, it doen’t stop on a breakpoint and the results are not stored on the database, the code works when is not executed on a test.

There is any problem to execute commans on phpunit, should I configure anything??

public function testUploadResults():void{
        
        
        //set api key in header
       
        $crawler = $this->client->request( Request::METHOD_GET, '/en/upload-result');

        //test if response is ok
        $this->assertEquals(200, $this->client->getResponse()->getStatusCode());
 
        //get the form
        $form = $crawler->selectButton('Upload')->form();

        $form['analysis[type]']->setValue('TYPE1');
        $form['analysis[file]']->setValue(new UploadedFile('/var/www/test_files/test.csv', 'test.csv', 'text/csv'));

        //submit form
        $this->client->submit($form);

        //test if response is ok
        $this->assertEquals(200, $this->client->getResponse()->getStatusCode());
        
        //probar que haya labresults para el test
        $results = $this->em->getRepository('AppBundle:Result')->findBy(['sample' => 'XXXX']);
        $this->assertTrue( count($results)>1 );
    }

How can fetch mutiple row data and insert each of them automatically to another table php mysql [closed]

I am trying to make a function where:

  • in the session if the date of the session is equal to the current data, the function will get all the data that the session is today, and then
  • each of those data items will be inserted to another table which is the notification table
  • then it will input the session id and the username to that table automatically

Search through laravel relationship with filtered date

i search data 1 (this exist in database) within date range of 13-04-2022 to 14-04-2022 (there is no data in this date range). From this query that i used on my controller still return the data that contains a keyword that i search for (data 1). What i wanted is to return collection of data with the range of the date filter (which is nothing since i dont have any data from that date range).
How to solve this problem? is there any best practices that i could implement for this search within the filtered date?
this is my back-end :

$rekans = Rekan::query()
                    ->join('dokters','dokters.id','=','rekans.dokter_id')
                    ->join('pasiens','pasiens.id','=','rekans.pasien_id')
                    ->join('penyakits','penyakits.id','=','rekans.dokter_id')
                    ->join('treatments','treatments.id','=','rekans.treatment_id');

    if(request('from_date')){
        $rekans->whereDate('rekans.created_at','>=',request('from_date'));
    }
    if(request('to_date')){
        $rekans->whereDate('rekans.created_at','<=',request('to_date'));
    }
    if(request('search')){
        $rekans->where('berat','LIKE','%'.request('search').'%')
            ->orWhere('rekan_inv','LIKE','%'.request('search').'%')
            ->orWhere('suhu','LIKE','%'.request('search').'%')
            ->orWhere('hasil_pemeriksaan','LIKE','%'.request('search').'%')
            ->orWhere('anamnesa','LIKE','%'.request('search').'%')
            ->orWhere('pengobatan','LIKE','%'.request('search').'%')
            ->orWhere('kasus','LIKE','%'.request('search').'%')
            ->orWhere('dokters.nama_dokter','LIKE','%'.request('search').'%')
            ->orWhere('pasiens.nama','LIKE','%'.request('search').'%')
            ->orWhere('penyakits.nama_penyakit','LIKE','%'.request('search').'%')
            ->orWhere('treatments.nama_treatment','LIKE','%'.request('search').'%');
    }

this is my sql

select * from `rekans` inner join `dokters` on `dokters`.`id` = `rekans`.`dokter_id` inner join `pasiens` on `pasiens`.`id` = `rekans`.`pasien_id` inner join `penyakits` on `penyakits`.`id` = `rekans`.`dokter_id` inner join `treatments` on `treatments`.`id` = `rekans`.`treatment_id` where date(`rekans`.`created_at`) >= ? and date(`rekans`.`created_at`) <= ? and `berat` LIKE ? or `rekan_inv` LIKE ? or `suhu` LIKE ? or `hasil_pemeriksaan` LIKE ? or `anamnesa` LIKE ? or `pengobatan` LIKE ? or `kasus` LIKE ? or `dokters`.`nama_dokter` LIKE ? or `pasiens`.`nama` LIKE ? or `penyakits`.`nama_penyakit` LIKE ? or `treatments`.`nama_treatment` LIKE ? order by `rekans`.`created_at` desc