Set default value in laravel views filter

Default Filter Value Not Working in Laravel Views

I’m trying to add a default value to a filter in Laravel Views, but it’s not working as expected. Here’s my current implementation:

GruposActiveFilter class:

use LaravelViewsFiltersFilter;
use IlluminateDatabaseEloquentBuilder;

class GruposActiveFilter extends Filter
{
    public function apply(Builder $query, $value, $request): Builder
    {
        return $query->where('Activo', $value);
    }

    public function options(): array
    {
        return [
            'Activo' => 1,
            'Inactivo' => 0,
        ];
    }
}

In my ListView:

protected function filters()
{
    return [
        new GruposActiveFilter,
    ];
}

What I’ve tried:

I’ve attempted to add a default() method to the filter class, but it doesn’t seem to be recognized:

public function default()
{
    return 1;
}

Expected behavior:

I expect the filter to default to ‘Activo’ (value 1) when the page is first loaded.

Actual behavior:

The filter is not applying any default value, and I have to manually select a filter option each time.

How can I set a default value for my GruposActiveFilter in Laravel Views so that it’s applied automatically when the page loads?

Any help or guidance would be greatly appreciated!

Using Php, How to change permission of Folder(and it’s files) to 755 to prevent deletion fo file from outside virus? And how to return to 777?

How to change permission of Folder(and it’s files) to 755 to prevent deletion of file from outside virus? And how to return to 777?
Want to use 777 only when necessary inside of php code.

Assuming file 333.jpg location in “image” Folder,

bellow should “not” delete file, 333.jpg?

<?php 
chmod("./image/" , 0755);
unlink("./image/333.jpg");
?>

For return to normal, bellow should delete file?

<?php
chmod("./image/" , 0777);
unlink("./image/333.jpg");
?>

BUT ABOVE CODES IS NOT WORKING..
Am running php under linux.
Thnaks in advance.

When i change permission through terminal by
“sudo chmod 755 /var/www/html/image”
it works. But not through php,,,,

My uploaded images are rotated with laravel / intervention

I am using intervention to manipulate some images with Laravel 11.

My code works fine in local environment.

When I deploy the application in production (heroku), the same code produces a surprising phenomenon: the image undergoes a rotation, sometimes by 90°, sometimes by 180°.

And the same image is not rotared locally, but is in production !

I tried to play with the “autoOrientation” parameter, without success. The image is still rotated.

My code is very simple :

$manager = new ImageManager(new Driver);
$image = $manager->read($media);
$image->save('transformed_image');

I read here and there that there is a story about “exif” data. Is this an indication ?

What could be my mistake ?

403 when downloading a file via PHP but not from browser

I have a 403 error when downloading a JSON file via PHP from a URL. I can open the file from the browser without problems (no errors in the dev tools).

This is the script (minus the actual URL), which I have verified as working with other sites:

$ch = curl_init($url);
$dir = '../sources/';
$file_name = basename($url);
$save_file_loc = $dir . $file_name;
$fp = fopen($save_file_loc, 'wb');
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
// curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_CAINFO, 'C:/Program Files/php/cacert.pem');
curl_exec($ch);
echo curl_errno($ch)."n";
print_r(curl_getinfo($ch));
curl_close($ch);
fclose($fp);

The certificate comes from https://curl.se/docs/caextract.html. This is the info I get:

    [url] => the/url/path/to/json/file
    [content_type] => text/html
    [http_code] => 403
    [header_size] => 183
    [request_size] => 83
    [filetime] => -1
    [ssl_verify_result] => 0
    [redirect_count] => 0
    [total_time] => 0.516273
    [namelookup_time] => 0.065622
    [connect_time] => 0.091481
    [pretransfer_time] => 0.483309
    [size_upload] => 0
    [size_download] => 418
    [speed_download] => 809
    [speed_upload] => 0
    [download_content_length] => 418
    [upload_content_length] => 0
    [starttransfer_time] => 0.516216
    [redirect_time] => 0
    [redirect_url] =>
    [primary_ip] => (the.url.primary.ip.address)
    [certinfo] => Array
        (
        )

    [primary_port] => 443
    [local_ip] => (my.local.ip)
    [local_port] => 65046
    [http_version] => 3
    [protocol] => 2
    [ssl_verifyresult] => 0
    [scheme] => HTTPS
    [appconnect_time_us] => 483121
    [connect_time_us] => 91481
    [namelookup_time_us] => 65622
    [pretransfer_time_us] => 483309
    [redirect_time_us] => 0
    [starttransfer_time_us] => 516216
    [total_time_us] => 516273
    [effective_method] => GET

Of course I tried setting a user agent as well, but no chance.

What am I missing?

Session change in php not caught in while loop

Trying to implement Server Side Events – On the server side (php), the below while loop doesn’t catch when the session is changed from another php script. It does catch it when the whole web page is reloaded. The second code without the loop catches the session change. Any clues to why and how to handle?

Not working code

<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
header('Connection: keep-alive');
    
function sendEvent($event, $data) {
    echo "event: $eventn";
    echo "data: $datann";
    ob_flush();
    flush();
}

// Check signing status and send events
while (true) {
    session_start();  // Reopen the session to get the latest data
    $status = $_SESSION['signing_status'];
    session_write_close(); // Immediately close the session to avoid locks
    
    sendEvent("event",$status);
    // Wait for a few seconds before checking again
    sleep(4);
}

?>

Working code

<?php
session_start();
$status = $_SESSION['signing_status'];
session_write_close();

header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
header('Connection: keep-alive');

$eventId = 0;  // Initialize event ID

sendEvent("event", $_SESSION['signing_status']);

function sendEvent($event, $data) {
    echo "event: $eventn";
    echo "data: $datann";
    ob_flush();
    flush();
}
?>

Hello, I have the following code, it is displaying data from the database but not adding data into the database [closed]

I have tried the code but not working. The select statement is working fine but the UPDATE And INSERT statements are not making any changes in the database.
Even the DELETE query made is not working. There is also a javascript file that contains code which then connects to this file below.

<?php

    include("db_connect.php");
    // handle a GET
    // add the header line to specify that the content type is JSON
    header("Content-type: application/json");

    // determine the request type
    $verb = $_SERVER["REQUEST_METHOD"];

    if ($verb == "GET") {
        $arr = array();

        $rs = mysqli_query($link,"SELECT s.id, s.name, s.local_church_id as l_id, l.name as local_church_name, l.id as local_church_id from small_christian_community s, local_church l WHERE s.local_church_id = l.id ORDER BY l.name ASC");
        while($obj = mysqli_fetch_object($rs)) {
            $arr[] = $obj;
        }

        // add the header line to specify that the content type is JSON
        header("Content-type: application/json");

        echo "{"data":" .json_encode($arr). "}";
    }

    if ($verb == "PUT") {

            $request_vars = Array();
            parse_str(file_get_contents('php://input'), $request_vars );
            $name = mysql_real_escape_string($request_vars["name"]);
            $local_church_id = mysql_real_escape_string($request_vars["local_church_id"]);



            // INSERT COMMAND
            $insert_query = "INSERT INTO small_christian_community(name, local_church_id) VALUES ('".$name."','".$local_church_id."')";

          $rs = mysqli_query($link,$insert_query);

          if ($rs) {
            echo json_encode($rs);
          }
          else {
            header("HTTP/1.1 500 Internal Server Error");
            echo false;
          }
    }
    if ($verb == "POST") {
            $name = mysql_real_escape_string($_POST["name"]);
            $local_church_id = mysql_real_escape_string($_POST["local_church_id"]);
            $id = mysql_real_escape_string($_POST["id"]);

            $rs = mysqli_query($link,"UPDATE small_christian_community SET name = '" .$name ."',local_church_id = '" .$local_church_id ."' WHERE id = " .$id);

            if ($rs) {
                echo json_encode($rs);
            }
            else {
                header("HTTP/1.1 500 Internal Server Error");
                echo "Update failed for church: " .$id;
            }
    }

    if ($verb == "DELETE") {
        parse_str(file_get_contents('php://input'), $_DELETE);
        $id = mysql_real_escape_string($_DELETE["id"]);

        $rs = mysqli_query($link,"DELETE FROM small_christian_community WHERE id = " .$id);

        if ($rs) {
            echo true;
        }
        else {
            header("HTTP/1.1 500 Internal Server Error");
            echo false;
        }
    }

?>

Someone please help

Send data from next js react hook form to php backend [duplicate]

I am trying to send data from a next js frontend to a php backend to populate my mysql database. I am trying to get it to connect but I am stuck as I am noob at php.

This is my next js form

const onSubmit = async (data: ShopFormValues) => {
        setLoading(true)
        try {        
            const response = await fetch("https://***********.com/register.php", {
                method: "POST",
                body: JSON.stringify({ firstname: "example" }),
                // ...
            });
            
            console.log(response)
        } catch (error: any) {
            console.log('Network error!')
        }
        finally {
            setLoading(false)
        }

    };

and this is my register.php file

<?php

    header("Access-Control-Allow-0rigin: *");
    header("Access-Control-Allow-Headers: *");

    $servername = "localhost";
    $database = "*********";
    $username = "************";
    $password = "************";
    $conn = new mysqli($servername, $username, $password, $database);
    
    if(isset($_POST['firstname'])){
        echo 'hello';
    }
    else {
        echo 'wa';
    }
?>

How can i confirm that the register.php file is receiving the data and send back a response?

wp event manager- stripe split pay issue connecting

I’m having issues with stripe split pay.
the website is a hub for organisers to come and post their events and sell tickets. the platform will take a percentage of the ticket sale and the rest will go to the event organiser. this was the main reason I bought the All Events Manager Pro.
Currently
-im getting a blank screen for the connect stripe as the organiser
stripe connect user/organiser interface to setup stripe connect and receive payouts from ticket sales

it should look like this:
this is from their website

-and the ‘you are not allowed’ as you are an admin as admin which is expected
this is the admin view of the stripe connect page

I am working in test mode and the stripe is connected. All the payment comes to my stripe account minus the stripe fees.
but they do not go to the organiser as there is no way to connect to the plaform.
stripe test mode dashbaord - demonstrating a correct api setup

I made a ticket and got a responce saying to “reinstall the wp event manager” but that would delete a lot of work….
please help me find a solution.

Many thanks

some resources from the themes website:

https://wp-eventmanager.com/knowledge-base/stripe-split-payment/#articleTOC_1
https://wp-eventmanager.com/set-up-stripe-wordpress/?srsltid=AfmBOopgkljGaAD5_1XUB73Cbd3HL06MynTiexOn8dMRzCNg4usoUAp7

How to make nuxt multiselect work properly with data from Laravel API?

I’m using the USelectMenu component from the Nuxt UI library, and I need to ensure that all the options that the user can select are displayed. I have that covered with my mapped_looking_for method, and the options are bound correctly. Then, I need to display all the options that the user has already selected, which I also have working to some extent.

The problem is that the select should work in such a way that if an option is selected, there should be a tick next to it on the right indicating that it is indeed selected. However, even though it shows that 5 options are selected, I don’t see the tick next to them. I am also unable to interact with them in such a way that I could remove options. Essentially, it doesn’t work for me; I would have to manually delete them from the database.

Could anyone offer some advice? I’m relatively new to working with APIs, and I might be passing the data incorrectly. Thank you.

This is frontend.

 <USelectMenu v-model="looking_fors" :options="mapped_looking_for" multiple
                    :placeholder="getLookingForPlaceholder" />

<script>
const mapped_looking_for = ref([]);

const looking_for = ref([]);

const fetchLookingFor = async () => {
    try {
        const { data } = await api.get('/api/lookingFor');
        mapped_looking_for.value = data.data.map(item => ({
            label: item.name,
            value: item.id
        }));
        console.log('Mapped looking_for:', mapped_looking_for.value);
    } catch (error) {
        console.error('Error fetching looking for options:', error);
    }
};

const getLookingForPlaceholder = computed(() => {
    const count = profile.value.looking_fors?.length || 0;
    return count > 0 ? `${count} selected` : 'None';
});

const fetchProfile = async () => {
    try {
        const { data } = await api.get('/api/profiles/show');
        profile.value = data.profile;
        user.value = data.user;
        looking_for.value = data.profile.looking_fors.map(item => item.id); 
    } catch (error) {
        console.error('Error fetching profile:', error);
    }
};

const updateProfile = async () => {
    try {
        const looking_for_ids = looking_for.value.map(item => item.value);

       
        await api.put(`/api/profiles/${profile.value.id}/looking-for`, {
            looking_for: looking_for_ids
        });
        console.log('Profile updated successfully');
    } catch (error) {
        console.error('Error updating profile:', error);
    }
};
</script>

This is what I have on backend.

 public function updateLookingFor(Request $request): JsonResponse
{
    $user = $request->user();
    $profile = $user->profile;
    $validated = $request->validate([
        'looking_for' => 'array',
        'looking_for.*' => 'exists:looking_fors,id',
    ]);

    $profile->lookingFors()->syncWithoutDetaching($validated['looking_for']);

    return response()->json(['message' => 'Looking for updated successfully']);
}

// And route
    Route::put('/profiles/{id}/looking-for', [ProfileController::class, 'updateLookingFor']);

URL navigation behaving strange

I am working on my website. I have separate PHP files that handle rendering and are pointed to by an .htaccess configuration.

Options All -Indexes

RewriteEngine On
RewriteBase /alix

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^essays/?$ essay.php [QSA,NC,L]
RewriteRule ^essays/([^/]*)?$ essay.php?title=$1 [QSA,NC,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^books/?$ book.php [QSA,NC,L]
RewriteRule ^books/([^/]*)?$ book.php?title=$1 [QSA,NC,L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/$ index.php [R=301,L]

In the book.html, I have the following link:

<a href="books/hackers-and-painters-big-ideas-from-the-computer-age">Hackers & Painters: Big Ideas from the Computer Age</a>

When I access my page:

enter image description here

Then I try to navigate:

enter image description here

To open a specific URL under the books/ URL. Upon clicking, I get this in Firefox:

http://127.0.0.1/alix/books/books/hackers-and-painters-big-ideas-from-the-computer-age

This same behavior happens when I try to navigate between subpages as well:

E.g., navigating back to Essays from Books URL:

enter image description here

Main navigation is constructed from this:

$navigation_menu = array(
    "home" => "/alix",
    "essays" => "essays",
    "books" => "books",
);

Manage custom stock conflict WooCommerce

I have created custom bookings tables.

Table Structure

wp_et_bk_bookings
    id - PK
    order_id - FK
    from_time
    to_time
    booking_date
    user_id - FK
    product_id - FK
    status

wp_et_bk_bookings_details
    id - PK
    et_bk_bookings_id - FK
    et_bk_event_ticket_types_dates_id - FK
    ticket_type_name
    quantity

I have two hooks used for block the stock exausts

In process_woocommerce_checkout_order_processed() once order confirmed I have added the booking.

But when user clicked place order for same ticket at same time it conflict and my stock gone in minus.

<?php
add_action('woocommerce_before_checkout_process', 'custom_remove_exhausted_booking_items');
add_action('woocommerce_checkout_order_processed', 'process_woocommerce_checkout_order_processed', 10, 1);

function custom_remove_exhausted_booking_items()
{
   global $wpdb;

   $wpdb->query('START TRANSACTION');

   $exhausted = false;
   foreach (WC()->cart->get_cart() as $cart_item_key => $cart_item) {
      $current_quantity = $cart_item['quantity'];

      $time_slot_id = isset($cart_item['time_slot_id']) ? $cart_item['time_slot_id'] : null;
      $et_bk_event_ticket_types_dates_id = isset($cart_item['et_bk_event_ticket_types_dates_id']) ? $cart_item['et_bk_event_ticket_types_dates_id'] : null;

      if (! $time_slot_id || ! $et_bk_event_ticket_types_dates_id) {
         continue;
      }

      $ticket_types = $wpdb->get_results("
            SELECT tt.*, ttd.id AS et_bk_event_ticket_types_dates_id, ttd.date, ttd.price AS date_price, ttd.quantity AS date_quantity, ttd.deposit_amount AS date_deposit 
            FROM {$wpdb->prefix}et_bk_event_ticket_types tt
            LEFT JOIN {$wpdb->prefix}et_bk_event_ticket_types_dates ttd ON tt.id = ttd.et_bk_event_ticket_types_id
            WHERE tt.et_bk_event_timeslots_id = $time_slot_id
            AND ttd.id = $et_bk_event_ticket_types_dates_id
            ORDER BY tt.sort_order ASC
        ");

      if (empty($ticket_types)) {
         continue;
      }

      foreach ($ticket_types as $ticket) {
         $booked_quantity = $wpdb->get_var("
                SELECT SUM(bd.quantity)
                FROM {$wpdb->prefix}et_bk_bookings b
                INNER JOIN {$wpdb->prefix}et_bk_bookings_details bd ON b.id = bd.et_bk_bookings_id
                WHERE bd.et_bk_event_ticket_types_dates_id = {$ticket->et_bk_event_ticket_types_dates_id}
                AND b.status IN ('pending', 'processing', 'on-hold', 'completed')
            ");
         $booked_quantity += $current_quantity;
         if ($booked_quantity > $ticket->date_quantity) {
            WC()->cart->remove_cart_item($cart_item_key);
            $exhausted = true;
         }
      }
   }
   if ($exhausted) {
      $wpdb->query('ROLLBACK');
      throw new Exception('Some items in your cart are no longer available for booking. Please review your cart and try again. <script>setTimeout(() => { location.reload(); }, 1000);</script>');
   } else {
      $wpdb->query('COMMIT');
   }
}

function process_woocommerce_checkout_order_processed($order_id)
{
$inserted = $wpdb->insert(
         $wpdb->prefix . 'et_bk_bookings',
         array(
            'order_id'     => $order_id,
            'time_slot_id' => $time_slot_id,
            'time_slot'    => $time_slot,
            'booking_date' => date('Y-m-d', strtotime($booking_date)),
            'user_id'      => $user_id,
            'product_id'   => $product_id,
            'from_time'    => $time_slot_details->from_time,
            'to_time'      => $time_slot_details->to_time,
            'status'       => $status
         ),
         array(
            '%d',
            '%d',
            '%s',
            '%s',
            '%d',
            '%d',
            '%s',
            '%s',
            '%s',
         )
      );
      if ($inserted) {
         $booking_id = $wpdb->insert_id;

         $future_payment_total = 0;

         foreach ($original_order->get_items() as $item_id => $item) {
            $ticket_type_name = $item->get_meta('ticket_type_name');
            $et_bk_event_ticket_types_dates_id = $item->get_meta('et_bk_event_ticket_types_dates_id');

            // Insert multiple entries in event_ticket_bookings_details
            $wpdb->insert(
               $wpdb->prefix . 'et_bk_bookings_details',
               array(
                  'et_bk_bookings_id'         => $booking_id,
                  'et_bk_event_ticket_types_dates_id' => $et_bk_event_ticket_types_dates_id,
                  'ticket_type_name'          => $ticket_type_name,
                  'quantity'                  => $item->get_quantity()
               ),
               array(
                  '%d',
                  '%d',
                  '%s',
                  '%d'
               )
            );

            // Retrieve future payment from meta and convert to float
            $future_payment = $item->get_meta('future_payment');
            $future_payment = preg_replace('/[^d.]/', '', $future_payment); // Clean up the future payment value
            $future_payment = floatval($future_payment);

            if ($future_payment) {
               $future_payment_total += $future_payment * $item->get_quantity();
            }
         }

Note – If user at different time only added in cart and then try to place order then it wont allowed.

WordPress REST API The POST Method doesn’t work

I used following script for REST API for POST Method in my existing method. this message is showing “”No route was found matching the URL and request method.”,” where is the error. I have already “save change” in the Permalink. various way verify my code which is corrected. same error is showing

class Class_dashboard { 

    public function __construct() {
       $this->display_latest_post();
       add_action('rest_api_init', array($this, 'lincense_register_routes'));   
    }  

    public function lincense_register_routes() {
        register_rest_route('license/v2', '/verify/', array(
            'methods' => 'POST',
            'callback' => array($this, 'verify_license_key'),
            'permission_callback' => '__return_true',
        ));
    }

    public function verify_license_key(WP_REST_Request $request) {
        header("Access-Control-Allow-Origin: *");  // Allow requests from any origin
        header("Access-Control-Allow-Methods: POST, GET");
        header("Access-Control-Allow-Headers: Content-Type");

        $license_key = sanitize_text_field($request->get_param('license_key'));
        //$license_key === '06078F5C173B8B98BFA8';
        global $wpdb;
        $table_name = $wpdb->prefix . 'woo_license_item';
    
        $result = $wpdb->get_row(
            $wpdb->prepare("SELECT * FROM $table_name WHERE licenseKey = %s", $license_key)
        );

        if ($result) {
            // Check if the license is active and not expired
            //if ($result->keystatus === 'close' && (empty($result->expiration_date) || strtotime($result->expiration_date) > time())) {
            if ($result->keystatus === 'close') {
                return new WP_REST_Response(array('status' => 'valid', 'message' => 'License is valid'), 200);
            } else {
                return new WP_REST_Response(array('status' => 'expired', 'message' => 'License has expired'), 200);
            }
        } else {
            return new WP_REST_Response(array('status' => 'invalid', 'message' => 'License key not found'), 200);
        }
    }
}

I cant find the error. why showing error again and again

Aliases for table fields in CakePHP4

In my DB I have a table page_content with a column which is a reserved MySQL 8 word, row.
Due to constraints mandated by my hosting system, I need to rename the column to something that isn’t a reserved word (my idea is to rename it to sort_row).

This row field is however, exposed by an API that my software is implementing and exposing. This API serializes the CakePHP ORM objects as JSON to expose them, which means, if I change the name of a field in my model class it will then also change accordingly in the JSON output of my API.
But I don’t want to rename the field in the API, because this would mean having to check and update every system which uses it.

The project is implemented with PHP8 and CakePHP 4.4.
I have an entity class for the table:

<?php

namespace AppModelEntity;

class PageContent extends Entity
{
    protected $_accessible = [
        '*' => true,
        'id' => false
    ];

    protected $_virtual = ['content'];

    protected $_hidden = [
        'is_visible',
        'visible_from',
        'visible_to',
        'is_deleted',
        'created',
        'modified',
        'created_user',
        'modified_user',
    ];

    protected function _getContent()
    {
        // method logic here
    }

    // more stuff here....
}

Is there any way I can specify an “alias” or something similar for my CakePHP model, so that while the MySQL field is called sort_row, as far as CakePHP is concerned (in ORM queries and so on) the field is still called row?
The documentation doesn’t really mention anything like that.
Can I use a virtual field to achieve what I need?

IONOS ftp-login via PHP not working but the connection via FTP client like filezilla works?

We receive the message on all possible systems where we have stored FTP login data (shopify, xentral etc.):

Upload failed: FTP Error: 530 Login incorrect.

The access data is correct because the connection via FTP client like filezilla works.

This Script:

$ftp = ftp_ssl_connect(FTP_HOST);
//$ftp = ftp_connect(FTP_HOST);

if (false === $ftp) {
    throw new Exception('Unable to connect');
}

$login_result = ftp_login($ftp, FTP_USER, FTP_PASS);

if (true === $login_result) {
    echo "login ok<br>";
} else {
    throw new Exception('Unable to log in ' . __LINE__);
}

$cd = ftp_pwd($ftp);

echo $cd . "<br>";

ftp_close($ftp);

works well with all ftp access data from various test servers except IONOS access data.

the very poor IONOS support (call center) can do nothing.

Is anyone aware of anything that IONOS has changed?