Mode in Stripe API

What is the Mode parameter in Stripe API? When I test Stripe Api in laravel, it says:

Error sending request to Stripe: (Status 400) (Request req_XKxpoKv6C0eFDm) You must provide mode when using prices. StripeExceptionInvalidRequestException: You must provide mode when using prices.

Here is my code:

  $session = Session::create([
                    'payment_method_types' => ['card'],
                   
                    'line_items' =>  [
                        [
                           
                         'price_data' => [
                          
                           'unit_amount' => $secretPlan['amount'] * 100,
                           'currency' => $secretPlan['currency'],
                           'product_data' => [
                             'name' => $secretPlan['name'],
                             'description' => $secretPlan['description']
                           ]
                         ],
                         'quantity' => $secretPlan['quantity'],
                        
                        ],
 
                     ],
                    'success_url' => $successURL,
                    'cancel_url' => route('payment.cancel')
                ]);

Can anyone give me a solution? Thanks in advance.

what is the difference between policy and gate laravel

hi all I learned laravel policy and Gates but I don’t know what the main difference between them

I try both policy and gates but I do not know what the main difference between them can anyone
could you help me in that?
is the main difference is that policy for one model but gate for multiple models??

Prevent Session Destruction on Specific Routes

I want to destroy the session on all routes except certain I have created a middleware for this

 public function handle(Request $request, Closure $next)
{
$currentRouteName = $request->route()->getName();


if ($currentRouteName !== 'wasteGenerationImpact.store' && $currentRouteName !== 'wasteGenerationImpact.index')
{
    // Destroy the session when the condition is met
    Session::forget(['reportingPeriodId', 'reportingPeriodName']);
}

return $next($request);
}

 Route::prefix('wasteGenerationImpact')->name('wasteGenerationImpact.')->group(function () {
    Route::get('/{wasteGenerationImpact?}', [WasteGenImpactController::class, 'index'])->name('index');
    Route::get('/store', [WasteGenImpactController::class, 'store'])->name('store');
    Route::post('/update/{id}', [WasteGenImpactController::class, 'update'])->name('update');
    Route::get('/delete/{id}', [WasteGenImpactController::class, 'destroy'])->name('destroy');
    Route::get('/restore/{id}', [WasteGenImpactController::class, 'restore'])->name('restore');
});

Session not destroying on index method but destroying on store.
I don’t want to destroy session when user is in wasteGenerationImpact’s routes

php PDO connect database via socks5 proxy

I’m trying to connect to a remote database(mysql, clickhouse, oracle) through PDO,i can’t use ssh tunnel because of the Internet Policy of my company,i can only use socks proxy like 3proxy to transfer my db connect request, is there any way to connect db using php PDO via socks5 proxy?

i try use PDO like this, using custom socket context, but not work

$db = new PDO($dsn, $username, $password, $options, $context);

Error: count(): Argument #1 ($value). When using form builder type collection

I’m using library kristijanhusak/laravel-form-builder and having a problem with ONE TO ONE (Polymorphic). It shows error “count(): Argument 1 ($value) must be of type Countable|array, MekongdeltaSlugModelsSlug given” like image bellow.

enter image description here

This is my database structure.

posts

  • id – integer
  • name – string

slugs

  • id – integer
  • url – string
  • sluggable_id – integer
  • sluggable_type – string

This is my buildForm
enter image description here

Trait sluggable and model Post
enter image description here

My environment

PHP 8.2

Laravel 10.25

“kris/laravel-form-builder”: “dev-master”,

I don’t know where I made a mistake or am missing something, can you help me?
Sorry for my English.
Thank you very much,

I want it to appear as a slug in the input text

How to store array data using laravel?

I am trying to store data of another table but it’s not working.I am new to laravel.

Please help me guys.

I have table named external_event_venues where i have column inside named amenities.

I have another table named venue_amenities where i have id as foreign key external_event_venue_id with column name amenity_id.

I assigned relationship between table is like this:
ExternalEventVenue.php

 public function amenities()
 {
     return $this->hasMany(VenueAmenities::class,'external_event_venue_id', 'id');
 }

I have create.blade file inside code for animities :

<x-forms.label fieldId="amenity" :fieldLabel="__('modules.venue.amenities')"      fieldName="amenities[]" fieldRequired="true">
</x-forms.label>
<div class="d-flex flex-wrap mb-3 ">
       @foreach(config('global.amenities') as $key => $value)
           <x-forms.checkbox :fieldLabel="$value" fieldName="amenities[]" fieldId="{{$key}}" fieldValue="{{$key}}"/>
       @endforeach
</div>

I have assigned array for it inside my global.php file :

<?php
    return[
          'amenities'  => [1 => 'Beachfront', 2 => 'A/V Equipement', 3 => 'Handicap Accessible', 4     => 'Pet Friendly', 5 => 'Outdoor Space', 6 => 'Breakout rooms', 7 => 'Business Center', 8 => 'Cab', 9 => 'Rooftop',10 => 'Theater space' ,11 => 'Parking' ,12 => 'Media room',13 => 'Spa' ,14 => 'WiFi'],
];

I want to store array data using controller method :

public function store(Request $request)
    {
           ...
           $venue->amenities = $request->amenity;
           $venue->save();
           $venue = new ExternalEventVenue();
            if (isset($request->amenity_id)) {
            foreach ($request->amenity_id as $amenityId) 
            {
                if ($amenityId !== null) {
                    $amenity = new VenueAmenities();                    
                    $amenity->amenity_id = $amenityId;
                    $amenity->external_event_venue_id = $venue->id;
                    $amenity->save();
                }
            }
        }
    }

Please anyone can help me with this…

make changes, appear in chatify chat application in laravel

I am a laravel newbie and I have recently tried integrating the chatify chat application into my laravel project but when I try to make changes to the app.blade.php, the changes don’t appear to be applied. I have tried using all sorts of commands to clear cache but all in vein. can someone please help me out?

I used the following artisan commands;

php artisan cache:clear
php artisan view:clear
php artisan config:clear

started the server over and again but all failed.

how to overwrite data form link to another link in php

hello i want want to overwrite all peramters from old link to new link .. like

$oldURl="https://example.com/abcd/data?p=123&x=ABCDSS";

$newUrl="https://example.com/?data=1&data2=2&data3=3";

// $fnialurl=rewrite_data($oldURl,$newUrl);

final result i want ..
https://example.com/abcd/data?data=1&data2=2&data3=3&p=123&x=ABCDSS

you have any idea to get path & request from old url and replace it in new url

How can i load a session without refresing a whole div inside which the session is stored?

<div class="row" id="getsum">
    <?php $i=0;$j=0;  
    $sum=Session::get('sumofac');
    // dd($sum);
    echo 'sum= '.$sum; 

    foreach(@$vehicles as $vehicle_details) {$i++; if($vehicle_details->is_airport_trips == 1 && $vehicle_details->is_private_airport==1 ) { 
      echo ' inside private ';
      ?>
    <div class=" col-sm-12 col-md-12 col-lg-3 @if($vehicle_details->is_shared_airport) shared_airport_yes @endif 
    @if($vehicle_details->is_private_airport) <?php $j++;?> private_airport_yes @endif">
    <div class="shared_airport_box vehicles shared_vehicles text-center @if($vehicle_details->is_shared_airport) shared_airport_yes @endif  @if($vehicle_details->is_private_airport) <?php $j++;?> private_airport_yes @endif" style="min-height: 400px;">
    <div class="options__container--option <?= ($i==1 || $j==1 && $vehicle_details->is_private_airport==1)?'checked11':'';?> " >
        <input id="chb1_{{$vehicle_details->id}}"  type="radio"  value="{{$vehicle_details->id}}" name="vehicle_id" data-value="{{$vehicle_details->minimum_hr}} !! {{$vehicle_details->psngr_price_1}} !! {{$vehicle_details->vehicle_name}}" class="shared_airport_box_label <?= ($i==1 || $vehicle_details->is_private_airport==1)?'autochecked':'';?>" >
        <label for="chb1_{{$vehicle_details->id}}" class="shared_airport_box_label">
            
       <img  src="{{ url('core/public/public/Image/'.$vehicle_details->image) }}">
        <h4 class="options__container--title"> {{@$vehicle_details->vehicle_name}}</h4><p> {{ @$vehicle_details->description}}</p>
       
   <p><span style="font-weight: bold;" id="shared_price_{{$vehicle_details->id}}">  </span></p>
   </label>
  </div>

  </div>
</div>



    <?php } 
    
    } ?> </div>            <!-- getsumdivends -->

this is my div in which a have stored the session from the controller when i refresh the page i only want $sum=Session::get(‘sumofac’); to change not the whole div and
i then need to use the $sum inside an if case
for eg: if($vehicle_details->maxpassengers >= $sum ) then show the rest of the div below.

Thanks in advance!!!

How to update on doctrine’s persist method by custom field

Good morning,

normally on $em->persist($variable) doctrine checks the id field if the entry exist. In my case, i get the entries to insert/update from a file where a id, named òld_id by example. This id is stored in my Database.

Now i try to update the db entries where doctrine should compare the old_id field from database and file.

Is this possible?

I could fetch all database entries before persist() and compare myself. But if is there a better solution, maybe to set a custom id field i would try this.

Woocommerce add request for product on cart page

Hi I have the latest wordpress and woocommerce versions as of today,
My question is how can I add a text area to the cart page for the client to full in if they are looking for a product that we do not have on our website. this should also show on view order. and on the emails to the client and to admin of the website.

I have the following code that shows on the cart page but it does not carry over to the view order and emails at all

what I have tried is the following

// Add custom fields to the cart item data
function custom_add_to_cart_item_data($cart_item_data, $product_id, $variation_id)
{
    if (isset($_POST['request_product']) && $_POST['request_product'] === 'yes') {
        $cart_item_data['custom_request'] = array(
            'product_name' => sanitize_text_field($_POST['custom_product_name']),
            'quantity' => intval($_POST['custom_quantity']),
        );
    }
    return $cart_item_data;
}
add_filter('woocommerce_add_cart_item_data', 'custom_add_to_cart_item_data', 10, 3);

// Display custom fields in the cart
function custom_render_cart_item($title, $cart_item, $cart_item_key)
{
    if (isset($cart_item['custom_request'])) {
        $title .= '<br><strong>Custom Request:</strong>';
        $title .= '<br>Product: ' . esc_html($cart_item['custom_request']['product_name']);
        $title .= '<br>Quantity: ' . esc_html($cart_item['custom_request']['quantity']);
    }
    return $title;
}
add_filter('woocommerce_cart_item_name', 'custom_render_cart_item', 10, 3);

I get bad request when I use this string with socket

I am trying to implement Fire and Forget in PHP, and I use this code (found here):

$parts = parse_url($url);
try {
    $socket = $this->openSocket($parts['host'], ($parts['port'] ?? $parts['scheme'] === 'https' ? 443 : 80));
} catch (Exception $e) {
    $socket = null;
}

if (!$socket) {
    return false;
}

$jsPostData = json_encode($postData, JSON_THROW_ON_ERROR);

$contentLength = strlen($jsPostData);

$request = "POST {$parts['path']} HTTP/1.1rn";
$request .= "Host: {$parts['host']}rn";
$request .= "Authorization: Bearer " . $bearerToken . "rn";
$request .= "Content-Length: {$contentLength}rn";
$request .= "Content-Type: application/jsonrnrn";
$request .= $jsPostData;

fwrite($socket, $request);
fclose($socket);        
    

It results with a request like this:

POST /my_path HTTP/1.1
Host: my_url
Authorization: Bearer my_bearer_token
Content-Length: 263
Content-Type: application/json

{"event":"...."}

I get the error:

HTTP/1.1 400 Bad Request
Server: awselb/2.0
Date: Fri, 06 Oct 2023 09:43:17 GMT
Content-Type: text/html
Content-Length: 220

I do not know if its a really bad request or its a permissions fail.

PHP Warning: Undefined array key “log_threshold” how to solve it?

Hello i have recently works on some script in localhost and whend i load the page i got “HTTP ERROR 500”

So i tried to look on apache logs and i saw this :[php:warn] [pid 6384:tid 1932] [client 127.0.0.1:63934] PHP Warning: Undefined array key "log_threshold" in C:\xampp\htdocs\xenfo.club\system\core\Log.php on line 138 [Fri Oct 06 09:00:39.006579 2023] [php:warn] [pid 6384:tid 1932] [client 127.0.0.1:63934] PHP Warning: Undefined array key "log_threshold" in C:\xampp\htdocs\xenfo.club\system\core\Log.php on line 142 [Fri Oct 06 09:00:39.261375 2023] [php:error] [pid 6384:tid 1932] [client 127.0.0.1:63934] PHP Fatal error: Array and string offset access syntax with curly braces is no longer supported in C:\xampp\htdocs\xenfo.club\public\src\service\Google_Utils.php on line 58 [Fri Oct 06 09:00:40.385679 2023] [php:warn] [pid 6384:tid 1952] [client 127.0.0.1:63933] PHP Warning: Undefined array key "log_threshold" in C:\xampp\htdocs\xenfo.club\system\core\Log.php on line 138, referer: https://xenfo.club/service_worker.js [Fri Oct 06 09:00:40.385679 2023] [php:warn] [pid 6384:tid 1952] [client 127.0.0.1:63933] PHP Warning: Undefined array key "log_threshold" in C:\xampp\htdocs\xenfo.club\system\core\Log.php on line 142, referer: https://xenfo.club/service_worker.js

So i go to look up on all the lines :
In log.php : line 138 to line 147

if (is_numeric($config['log_threshold']))
        {
            $this->_threshold = (int) $config['log_threshold'];
        }
        elseif (is_array($config['log_threshold']))
        {
            $this->_threshold = 0;
            $this->_threshold_array = array_flip($config['log_threshold']);
        }

in Google_Utils.php line 47 to line 59

// Include the top level classes, they each include their own dependencies
require_once 'service/Google_Model.php';
require_once 'service/Google_Service.php';
require_once 'service/Google_ServiceResource.php';
require_once 'auth/Google_AssertionCredentials.php';
require_once 'auth/Google_Signer.php';
require_once 'auth/Google_P12Signer.php';
require_once 'service/Google_BatchRequest.php';
require_once 'external/URITemplateParser.php';
require_once 'auth/Google_Auth.php';
require_once 'cache/Google_Cache.php';
require_once 'io/Google_IO.php';
require_once('service/Google_MediaFileUpload.php');

If someone know something pls help me to fix this

Frameworks: CodeIgniter (PHP)

Server: Xampp

An also i can’t find service_worker.js
Any idea to create one ?

Thanks in advance

Error fetching data with a POST request from React Native App to PHP Api

I’m creating an app that must have a database in an online server.
On this server there this PHP Api:

<?php
    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

    $request_service = $_POST["service"];
    
    $conn = getConnection();
    
    $rows = array();
    $query_result;

    switch ($request_service) {
    case "getTestOne":
        $query_result = getTestOne($conn);
        break;
    case "getTestTwo":
        $query_result = getTestTwo($conn);
        break;
    }
    
    //echo $query_result;
    echo parseResultToJson($query_result);
    
    $conn->close();
    
    function parseResultToJson($result) {
        while($r = mysqli_fetch_assoc($result)) {
        $returnRows[] = $r;
        }
        return json_encode($returnRows);
    }  
    
    function getConnection() {
        // the * are there for privacy, in the real code there are the real data
    $servername = "******";
        $username = "******";
        $password = "******";
        $database = "******";
        
        $o_conn = new mysqli($servername, $username, $password, $database);
        if ($o_conn -> connect_errno) {
            echo "Failed to connect to MySQL: " . $o_conn -> connect_error;
            exit();
        } 
        return $o_conn;
    }
    
    function getTestOne($i_conn) {
        $result = $i_conn->query("SELECT * FROM Test;");
        return $result;
    }
    
    function getTestTwo($i_conn) {
        $result = $i_conn->query("SELECT * FROM TestTwo;");
        return $result;
    }
?>

I try to send a POST request from my React Native app:

import { Component } from "react"
import { Button, Text, View } from "react-native";

export default class HomePage extends Component {

    constructor(props) {
        super(props);
        this.state = {

        }
        this.fetchData = this.fetchData.bind(this)
    }

    componentDidMount() {
    }

    fetchData() {    
        fetch("https://homey.altervista.org/testApi.php", {
            method: "POST",
            mode: "no-cors",
            headers: {
                "Accept": "application/json",
                "Content-type": "application/json"
            },
            body: JSON.stringify({
                service: "getTestOne"
            })
        })
        .then((response) => console.log((response)))
        .catch((error) => console.log("ERROR: " + error));
    }

    render() {
        return (
            <View>
                <Button
                    title={"Fetch Data"}
                    style={{width: 300, height: 100}}
                    onPress={this.fetchData}
                />
            </View>
        )
    }
}

but the response is:


{
    "type": "default",
    "status": 200,
    "ok": true,
    "statusText": "",
    "headers": {
        "map": {
            "content-type": "text/html; charset=UTF-8",
            "date": "Fri, 06 Oct 2023 09:10:07 GMT",
            "server": "Apache",
            "vary": "Accept-Encoding"
        }
    },
    "url": "https://homey.altervista.org/testApi.php",
    "bodyUsed": false,
    "_bodyInit": {
        "_data": {
            "size": 4,
            "offset": 0,
            "blobId": "f8086baf-3a86-4b59-b07b-531a884f082d",
            "__collector": {}
        }
    },
    "_bodyBlob": {
        "_data": {
            "size": 4,
            "offset": 0,
            "blobId": "f8086baf-3a86-4b59-b07b-531a884f082d",
            "__collector": {}
        }
    }
}

Using Postman it works perfectly:

I tried to convert the response using response.json() or response.blob() but it doesn’t work.