Eloquent query, access scope function from within subquery

I have the a scope function for my user table (User.php):

public function scopeWherePaidSubscriber(Builder $query)
{
    return $query->where(....)->where(...);
}

I am trying to access this scope from a subquery looking like this:

$count = UserCalendar::whereIn('user_id', function($que) use ($cid) { 
        $que->select('id')->from('user')->where('corporation_id', $cid)->wherePaidSubscriber();
    })->distinct('user_id')->count();

But then I noticed than I couldn’t access the scope because I am not using User::wherePaidSubscriber().
Is there a way for me to access the scope without having to copy paste it?

How to authenticate for FCM Rest API using API Key?

I need to send a notification using FCM REST API. However, I am unable to authenticaate using an API key at the moment. The below is the API to hit.

https://fcm.googleapis.com/v1/projects/proj-name/messages:send?key=XXX

The error I receive is as follows:

{
    "error": {
        "code": 401,
        "message": "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
        "status": "UNAUTHENTICATED"
    }
}

The backend is in PHP so there isn’t any supported package for it. Hence, I am trying to use it for sending the notification. The above API seem to take oauth 2 access token or login cookie or some auther vaidation method. However, I need to send it from my own REST API. How can I authenticate from PHP to the above API and send the notificaiton properly?

Can someone help Me with payment system with php and handling request [closed]

So i use payment method with midtrans and its works. the problem was to use handler/ request to update mysql, i need to change status database. Help me please…..

~
<?php 

namespace Midtrans;

    require('admin/inc/db_config.php');
    require('admin/inc/essentials.php');

    require('inc/midtrans/Midtrans.php');

    date_default_timezone_set("Asia/Jakarta");

    session_start();

    if(!(isset($_SESSION['login']) && $_SESSION['login']==true)){
        redirect('index.php');
    }

    if(isset($_POST['pay_now']))
    {
        Config::$serverKey = 'SB-Mid-server-cVWDFZurOiO0YqrkLCKn6qRS';
        Config::$clientKey = 'SB-Mid-client-mtGw2S9jLzeMkWx3';
        // Enable sanitization
        Config::$isSanitized = true;

        // Enable 3D-Secure
        Config::$is3ds = true;
        

        $CUST_ID = $_SESSION['uId'];
        $ORDER_ID =  'ORD_'.$_SESSION['uId'].random_int(11111,9999999);
        $gross_amount = $_SESSION['room']['payment'];


        $transaction_details = array(
            'order_id' => $ORDER_ID,
            'gross_amount' => $_SESSION['room']['payment'], // no decimal allowed for creditcard
        );

        $transaction_data = array(
            'transaction_details' => $transaction_details
          );

        $frm_data = filteration($_POST);

        $query1 = "INSERT INTO `booking_order`(`user_id`, `room_id`, `check_in`,`check_out`, `order_id`) VALUES (?,?,?,?,?)";

        insert($query1,[$CUST_ID,$_SESSION['room']['id'],$frm_data['checkin'],$frm_data['checkout'],$ORDER_ID],'issss');

        $booking_id = mysqli_insert_id($con);

        $query2 = "INSERT INTO `booking_details`(`booking_id`, `room_name`, `price`, `total_pay`,
            `user_name`, `phonenum`, `address`) VALUES (?,?,?,?,?,?,?)";
        
        insert($query2,[$booking_id,$_SESSION['room']['name'],$_SESSION['room']['price'],$gross_amount,$frm_data['name'],
            $frm_data['phonenum'],$frm_data['address']],'issssss');

        try {
            $snap_token = Snap::getSnapToken($transaction_data);
        } catch (\Exception $e) {
            echo $e->getMessage();
        }
       
    }
?>

<!DOCTYPE html>
<html>
    <body>
        <button id="pay-button">Pay!</button>
        <pre><div id="result-json">JSON result will appear here after payment:<br></div></pre> 

        <!-- TODO: Remove ".sandbox" from script src URL for production environment. Also input your client key in "data-client-key" -->
        <script src="https://app.sandbox.midtrans.com/snap/snap.js" data-client-key="<?php echo Config::$clientKey;?>"></script>
        <script type="text/javascript">
            document.getElementById('pay-button').onclick = function(){
                // SnapToken acquired from previous step
                snap.pay('<?php echo $snap_token?>', {
                    // Optional
                    onSuccess: function(result){
                        
                        $frm_data = filteration($_POST);

                        $q = "UPDATE `booking_order` SET `transaction_status`='paid' WHERE `order_id`=? ";
                        $values = [$frm_data['transaction_status']];
                        $res = update($q,$values,'ss');
                       
                        /* You may add your own js here, this is just example */ 
                        console.log('success');console.log(result);
                        // document.getElementById('result-json').innerHTML += JSON.stringify(result, null, 2);
                       
                        
                    },
                    // Optional
                    onPending: function(result){
                        /* You may add your own js here, this is just example */ 
                        // document.getElementById('result-json').innerHTML += JSON.stringify(result, null, 2);
                        console.log('pending');console.log(result);
                    },
                    // Optional
                    onError: function(result){
                        /* You may add your own js here, this is just example */ 
                        // document.getElementById('result-json').innerHTML += JSON.stringify(result, null, 2);
                        console.log('error');console.log(result);
                    }
                });
            };
        </script>
    </body>
</html>

~

in_array(): Argument #2 ($haystack) must be of type array

Why am i having an

Type: TypeError
Message: in_array(): Argument #2 ($haystack) must be of type array, int given

my code is something like this hope someone can help i’m using codeigniter 3

<div class="form-group">
<label for="sub_category">Category:</label>
<?php $sub_category_data = json_decode($product_data['sub_category_id']); ?>
<select class="form-control select_group" id="sub_category_1" name="sub_category[]" onchange="getSubCategoryData(1)">
<?php foreach ($sub_category as $k => $v): ?>
<option value="<?php echo $v['id'] ?>" <?php if(in_array($v['id'], $sub_category_data)) { echo 'selected="selected"'; } ?>><?php echo $v['name'] ?></option>
<?php endforeach ?>
</select>
</div>

mailchimp api when moving member to new audience, member is not removed from old audience

When using the Mailchimp 3.0 api, if I move a member to a new list/audience using the ‘add or update list member’ endpoint, the old instance of the member is not removed from the old audience.

First I tried updating a member to a new group using the ‘add or update list member’. This resulted in there being the same member in 2 audiences. Next I tried retrieving all users from the other list, then checking if the user I wanted to add to a new group was found in there. Then remove that user from the old list and add the new member to the right audience. The problem with this is that the old user gets archived and cannot be added back using the same api call as before when the user is changed back to the old audience.

How do I edit the label and x-axis of a laravel/chart.js boxplot?

Chart.js translation for plotting on frontend side in Laravel. There is a yield of 3 months dates and their datas. How should I fit charjs that overlap and not all dates are written at the end of x? (texts are overlapping, i dont want it, and I want all the dates to be on the x-axis, I think chartjs skipped it because couldn’t fit it.) it is important can you contact with me

enter image description here

 var myChart1 = new Chart(ctx1, {
        type: 'bar',
        data: {
                labels: dates,
                datasets: [{
        label: 'BACKLOG ON HOLD INCIDENTS AVG PERFORMANCE- BURSA',
        data: results,
        backgroundColor: [
            'rgba(76, 196, 23, 0.6)'

        ],
        borderColor: [
            'rgba(219, 249, 219, 1)',

        ],
        borderWidth: 1,
                }]
        },
        plugins: [ChartDataLabels],
        options: {
                plugins:{
                legend:{
                        display:true
                },
        datalabels:{
                color:'blue',
                anchor:'end',
        font:{
                weight:'bold',
                size:14
             }
                  }
        },
        scales: {
        y: {
            beginAtZero: true
           }
        },
        animation: {
            duration: 0
        }
        }
    });

Error load Json data array from Php in Python

I have this data of array in php that converted to json

$dataraw = $_SESSION['image'];
$datagambar = json_encode($dataraw);
$escaped_json = escapeshellarg($datagambar);

Escaped_json output as strings:

"[{ FileName : 20221227_202035.jpg , Model : SM-A528B , Longitude :106.904251, Latitude :-6.167665},{ FileName : 20221227_202157.jpg , Model : SM-A528B , Longitude :106.9042428, Latitude :-6.167658099722223}]"

Datagambar output as array :

[{"FileName":"20221227_202035.jpg","Model":"SM-A528B","Longitude":106.904251,"Latitude":-6.167665},{"FileName":"20221227_202157.jpg","Model":"SM-A528B","Longitude":106.9042428,"Latitude":-6.167658099722223}]

I want to call it to python, this is my py code

escaped_json = sys.argv[1] 
parsed_data = json.loads(escaped_json) 
print (parsed_data[0])

But from parsed_data = json.loads(escaped_json)
I get an error JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Is there any suggestions how to fix it?

How to get array from php to react axios?

Array
(
    [0] => Array
        (
            [images] => projects/0mxlk1duzt/1.png
        )

    [1] => Array
        (
            [images] => projects/0mxlk1duzt/2.png
        )

    [2] => Array
        (
            [images] => projects/0mxlk1duzt/3.png
        )
)

this is array what i have in php file on server, code in php

<?php
    header('Access-Control-Allow-Origin: *');
    header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
    header("Access-Control-Allow-Headers: Content-Disposition, Content-Type, Content-Length, Accept-Encoding");
    header("Content-type:application/json");

$response = array();
    foreach(glob('projects/0mxlk1duzt/*', GLOB_NOSORT) as $image)   
    {  
                  array_push($response,array(
                    "images" => $image
                  ));
    }  
    print_r($response); 
?>

next i have react app with axios with code:

class Gallery extends React.Component {
  state = {
    images: []
  }
  componentDidMount() {
    const url = 'http://work.eniso.ru/gallery.php'
    axios.get(url).then(response => response.data)
    .then((data) => {
      this.setState({ images: data })
      console.log(this.state.images)
     })
  }
  render(){
    return(
      <div className='gallery'>
        <ul>
          { this.state.images }
        </ul>
      </div>
    )
  }
}

now i can only output this in text format, but i don’t understand how to get array and in react i must do array.map to output elements in

  • Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, bool given in [duplicate]

    i want to select table with validation with id user

    `

    $id_user_login = $_SESSION['id_user'];        
                                        
    $activity=mysqli_query($con,
    "SELECT * FROM mai_activity
    JOIN mai_user ON mai_activity.id_user = mai_user.id_user
    JOIN mai_corporation ON mai_activity.id_corporation = mai_corporation.id_corporation
    JOIN mai_level_user ON mai_activity.id_level_user = mai_level_user.id_level_user 
    WHERE id_user = '$id_user_login'
    ORDER BY id_activity DESC");
    while ($data=mysqli_fetch_array($activity)){}
    

    `

    I get this error Warning: mysqli_fetch_array() expects parameter 1 to be mysqli_result, bool given at the while ($data….) statement.

    Error of key for an array where it’s not normal it doesn’t know that key

    I have an error where I’m not supposed to.
    I’m working with Symfony and need to separate information from a string.
    The error is:

    Warning: Undefined array key 2

    I get a string like this:

    $buffer = "y;;x;x;x;x;x;x;x;x;;y"
    

    I want to separate each x and each y in a variable so I splited the string in 3 by “;;” and the middle part in 8 by “;”. Like this:

    // get all information out of the string
    $separation = explode(";;", $buffer);
                    
    $usernameToAdd = $separation[0];
    $others = $separation[1];
    $notifRule = $separation[2];
                    
    // get all from others
    $allFromOthers = explode(';', $others);
    
    $var1 = $allFromOthers[0];
    $var2 = $allFromOthers[1];
    $var3 = $allFromOthers[2];
    $var4 = $allFromOthers[3];
    $var5 = $allFromOthers[4];
    $var6 = $allFromOthers[5];
    $var7 = $allFromOthers[6];
    $var8 = $allFromOthers[7];
    

    I got the error on key 2 of ‘$allFromOthers’ but if I switch lines I’ll get an error on the upper key but never on key 0 or 1.

    I tried to ‘dd’ my variables but everything was ok. I even noticed the strange error that lead me to the title of my post: if I put the ‘dd’ after the line with the error, everything works and I got my data on the screen, where I can see that my code works well. I don’t know how this is possible so if someone can help me with this it would be nice!

    how can i export button to show csv file in php

    How can i show to export button in csv file. Download Simple Export CSV file in PHP .

    Problem : file can not show only data printed on page. What’s the problem with the code? i can not understand.enter image description here

     function car_data_callback()
    // {
    
    //  //Database connections
    //  $database_server     = ""; 
    //  $database_username = ""; 
    //  $database_password = ""; 
    //  $database_name     = ""; 
     
    //  // Create database connection 
    //      $connection = mysqli_connect($database_server, $database_username, $database_password, $database_name);
    
    //  // Check connection
    //      if($connection === false)
    //      {
    //          die("ERROR: Could not connect. " . mysqli_connect_error());
    //      }
    
    //      $query = "SELECT * FROM wpsn_car_price_table";
    //      $result = mysqli_query($connection, $query);
    //      $number_of_fields = mysqli_num_fields($result);
    //      $headers = array();
            
    //      for ($i = 0; $i < $number_of_fields; $i++) 
    //      {
    //          $headers[] = mysqli_field_name($result , $i);
    //      }
    
    //      $fp = fopen('php://output', 'w');
    //      if ($fp && $result) {
            
    //          header('Content-Type: text/csv');
    //          header('Content-Disposition: attachment; filename="export.csv"');
    //          header('Pragma: no-cache');
    //          header('Expires: 0');
    //          fputcsv($fp, $headers);
    
    //          while ($row = $result->fetch_array(MYSQLI_NUM)) {
    //              fputcsv($fp, array_values($row));       
            
    //          }
    //          die;
    //      }
    
    //  }
    
    //      function mysqli_field_name($result, $field_offset)
    //          {
    //             $properties = mysqli_fetch_field_direct($result, $field_offset);
    //              return is_object($properties) ? $properties->name : null;
    //          }
    

    How can I read the XML in php? [closed]

    I cannot read the XML in php. I am getting a response in XML and I need to show it in a ul/li tag in php. Its like a order tracking API which is giving a response in XML format.

    <?php 
    $xml='<?xml version="1.0" encoding="utf-8"?>
    <vendor-objects version="1.0">
        <object vk="1"
                model="vb">
            <field type="BigIntegerField"
                   name="dono">12345</field>
            <field type="CharField"
                   name="pid">DHI89</field>
            <field type="FloatField"
                   name="dwei">1</field>
            <field name="xcvi">
                <object vk="1"
                        model="v_stage">
                    <field type="CharField"
                           name="serty">Item no</field>
                </object>
                <object vk="2"
                        model="v_stage">
                    <field type="CharField"
                           name="serty">P no</field>
                </object>
            </field>
        </object>
    </vendor-objects>
    ';
    
    
    $devices = array();
    $xml = simplexml_load_string($xml);
    foreach($xml->field->object as $item)
    {
       $device = array();
    
       foreach($item as $key => $value)
       {
            $device[(string)$key] = (string)$value;
       }
    
       $devices[] = $device;
    }
    print_r($devices);
    ?>
    

    How to restrict PHP mail from sending email to spam folder

    `I tried the code below but it is still sending to SPAM folder. Kindly help me to figure this out such that emails goes to INBOX only.

    function sendEmail($content,$email,$phone){
      $headers = "Reply-To: Danuel <".$email.">rn";
      $headers .= "Return-Path:Danuel <".$email.">rn";
      $headers .= "From:Danuel <".$email.">rn"; 
      $headers .= "Organization:Danuel internationalrn";
      $headers .= "MIME-Version: 1.0rn";
      $headers .= "Content-type: text/plain; charset=iso-8859-1rn";
      $headers .= "X-Priority: 3rn";
      $headers .= "X-Mailer: PHP". phpversion() ."rn";
      $to ="[email protected]";
      $subject ="Number ".$phone." Banned";
      return mail($to, $subject, $content, $headers);
    }
    
    if(isset($_POST['send'])){
        $content='Hey';
        
        if(sendEmail($content,$_POST['email'],$_POST['phone'])==1){
           echo"<small><font color=green>Sent</font></small>";
        }else{
           echo"<small><font color=red>Failed</font></small>";
        }
    }
    

    PHP Modify Variable

    There is a PHP file called test2.php,the code is in follow:

    <?php
    $data=array(
        'name' => 'jack',
        'age' => 8,
    );
    ?>
    

    I want to modify the $data in anoher php file called test1.php,
    but i find that if only use:

    require_once "./test2.php";
    $data['age']=10;
    echo $data['age'];
    

    Although the output is 10,but $data in test2.php dosen’t change.

    I want to know how to edit a PHP file in anoher PHP file.