Filter Products Dynamically according to attributes in Laravel with Query Builder

I have stored Products and their attributes, and attribute options as well in the database.

In this way, I sent product attribute_data into Database

Function

$data['product_attributes'] = Pro_attributes::with('attribute_options')->get();

Blade File (Displaying Data)

 @foreach ($product_attributes->unique('name') as $item)
<div class="sidebar__item sidebar__item__color--option">
<h4>{{ $item->name }}</h4>

@php
$options = $product_attributes
->where('name', $item->name)
->flatMap->attribute_options->unique('name')
->sortBy('name');
@endphp

@foreach ($options as $option)
<div class="form-check">
<input class="form-check-input" type="radio" value="{{ $option->id }}"
    id="{{ $option->id }}"
    name="{{ strtolower(str_replace(' ', '-', $item->name)) }}">
<label class="form-check-label"
    for="{{ $option->id }}">{{ $option->name }}</label>
</div>
@endforeach
</div>
@endforeach

Result

Frontend Displaying Attributes and options

Now After Submitting form dd($request->all());

array:4 [▼ // appHttpControllersFrontendShopController.php:59
  "color" => "47"
  "size" => "50"
]

as my relations are

from product.php

public function attributes()
{
    return $this->hasMany(Pro_attributes::class, 'product_id');
}

from pro_attibutes.php

public function attribute_options()
{
    return $this->hasMany(pro_attributes_options::class, 'attribute_id');
}

and from pro_attibutes_options.php

public function attribute()
{
    return $this->belongsTo(Pro_attributes::class, 'attribute_id');
}
public function product()
{
    return $this->belongsTo(Product::class, 'product_id');
}

Now Please help to Filter products dynamically having these attributes

as I have tried much to make this functionality but i can’t.

i do not want to filter this way

if ($request->filled('color')) {
$color = (array) $request->input('color');
$products->whereHas('attributes.attribute_options', function ($query) use ($color) {
$query->whereIn('id', $color);
});
}

because in this way we’ve to create code one by one for each attribute
but I want to make it dynamic because in the future I have to create more filters.

Please help me I am waiting for your response.

Email send via ajax or php

i need your help to fix the following problem. I want to send a varaible from js to php, because i want to use the mail function in php, so i have to send the text, which is computed in js to php.

Is there a possibility to using the ajax constructor or the xmlhttpRequest, and how is it working

how to make download link available in product page instead of add to cart button , after user purchased in woocommerce

I have an online woocommerce shop with downloadable products .
what I need is in single product page after a user purchased and bought a product , he can see his product download link available in single product page and add to cart button be eliminated .
actually I need some function to get get this condition ” user has bought this product ” and give me ability to do conditional task for this case .

now I am trying to use Jet engine dynamic content visibility and query builder .

I want to send some SQL queries from PHP in the simplest way but also safe [duplicate]

<?php
$route = $_POST["select-route"];
$currentStop = $_POST["current-bus-stop"];
date_default_timezone_set("Asia/Kolkata");
$currentTime = date("h:i A");

$host = "localhost";
$dbname = "findmybus-test";
$username = "root";
$password = "";
        
$conn = mysqli_connect(hostname: $host,
                       username: $username,
                       password: $password,
                       database: $dbname);
        
if (mysqli_connect_errno()) {
    die("Connection error: " . mysqli_connect_error());
}           
        
$sql = "INSERT INTO `findmybustest` (route, location, time)
        VALUES (?, ?, ?);";

$stmt = mysqli_stmt_init($conn);

if ( ! mysqli_stmt_prepare($stmt, $sql)) {
    die(mysqli_error($conn));
}

mysqli_stmt_bind_param($stmt, "sss",
                       $route,
                       $currentStop,
                       $currentTime);

mysqli_stmt_execute($stmt);

echo "Record saved.";
?>

But when I ran it, the screen turned white (probably because of one of my error catching if statements) but I cant see the errors. I am completely new to SQL queries so please tell me what is the syntax error.

Php 8.2.8 with Sql server

i have updated to php 8.2.8 , and here is php.ini modifiations to work with sql server :

uncomment :

extension_dir = "ext"

add :

extension=php_pdo_sqlsrv_82_nts.dll
extension=php_pdo_sqlsrv_82_ts.dll
extension=php_sqlsrv_82_nts.dll
extension=php_sqlsrv_82_ts.dll

then i got this error :

PHP Warning: PHP Startup: Unable to load dynamic library
‘php_pdo_sqlsrv_82_nts.dll’ (tried: extphp_pdo_sqlsrv_82_nts.dll (The
specified module could not be found),
extphp_php_pdo_sqlsrv_82_nts.dll.dll (The specified module could not
be found)) in Unknown on line 0 PHP Warning: PHP Startup: Unable to
load dynamic library ‘php_sqlsrv_82_nts.dll’ (tried:
extphp_sqlsrv_82_nts.dll (The specified module could not be found),
extphp_php_sqlsrv_82_nts.dll.dll (The specified module could not be
found)) in Unknown on line 0

note : i works on windows 10 64x , i made sure that (.dll) files are located correctly in their pathes , and finally before upadte php everything was working succesfully ..

Change PHP version after installing through make

I recently installed php 8.2.7 onto my Debian 10 server, compiling it from source and installing it through ‘make install’. I would now like to change this version but am unable to, installing a new version does not change it, nor does using update-alternatives. The command works and I am able to select a different version, yet the results of ‘php -version’ do not change. Help would be hugely appreciated.

How to loop through a multi-dimensional array and extract specific values on each loop? [duplicate]

I’m trying to learn how to use PHP arrays.

I have basically created a script that interogates an API, gets the resulting JSON data and then converts that into a PHP array.

The final array looks like:

Array
(
    [0] => stdClass Object
        (
            [age_range] => 
            [outcome] => A no further action disposal
            [involved_person] => 1
            [self_defined_ethnicity] => Other ethnic group - Not stated
            [gender] => Male
            [legislation] => 
            [outcome_linked_to_object_of_search] => 
            [datetime] => 2023-05-17T19:56:00+00:00
            [removal_of_more_than_outer_clothing] => 
            [outcome_object] => stdClass Object
                (
                    [id] => bu-no-further-action
                    [name] => A no further action disposal
                )

            [location] => stdClass Object
                (
                    [latitude] => 51.459157
                    [street] => stdClass Object
                        (
                            [id] => 2004699
                            [name] => On or near Parking Area
                        )

                    [longitude] => -0.478454
                )

            [operation] => 
            [officer_defined_ethnicity] => White
            [type] => Person search
            [operation_name] => 
            [object_of_search] => Controlled drugs
        )

    [1] => stdClass Object
        (
            [age_range] => 18-24
            [outcome] => A no further action disposal
            [involved_person] => 1
            [self_defined_ethnicity] => White - English/Welsh/Scottish/Northern Irish/British
            [gender] => Male
            [legislation] => 
            [outcome_linked_to_object_of_search] => 1
            [datetime] => 2023-05-12T22:19:00+00:00
            [removal_of_more_than_outer_clothing] => 
            [outcome_object] => stdClass Object
                (
                    [id] => bu-no-further-action
                    [name] => A no further action disposal
                )

            [location] => stdClass Object
                (
                    [latitude] => 51.434468
                    [street] => stdClass Object
                        (
                            [id] => 2003771
                            [name] => On or near Matthews Lane
                        )

                    [longitude] => -0.505257
                )

            [operation] => 
            [officer_defined_ethnicity] => White
            [type] => Person search
            [operation_name] => 
            [object_of_search] => Controlled drugs
        )

etc

I now basically want to loop through this array and for each entry grab [gender], [datetime], ]latitude], [longitude] and [officer_defined_ethnicity]

I have very little experience with PHP arrays, but I understand that I should be able to pull individual values using something like:

$array[0]["officer_defined_ethnicity"]

I could then wrap this into a loop.

But if I do something like:

$response_data = json_decode($json_data);
echo $response_data[0]["officer_defined_ethnicity"];

I just get an error.

Sorry if this is really basic, but I’m struggling to get a foothold as I can’t even seemingly output single values.

PHP Notice taking my website down: Function wpdb was called incorrectly [closed]

So every Friday at the very same time my website get’s down for almost 10 mins and then it goes back up by itself or I’ve to enable define('WP_ALLOW_REPAIR', false); and I repair the DB my self.

After enabling the debug log I’ve got almost 853 PHP notices at the same second (all the notices are at [07-Jul-2023 07:46:46 UTC]).
These first 654 notices are:
PHP Warning: mysqli_real_connect(): (HY000/2002): No such file or directory in /var/www/html/7awi/wp-includes/class-wpdb.php on line 2019.

What I’ve tried so far
“I’ve searched for this error on stack overflow and some people said they got rid of by changing the host in the wp-config from localhost to 127.0.0.1” this solution didn’t work for me.

And the rest notices are: PHP Notice: Function wpdb was called incorrectly. wpdb must set a database connection for use with escaping. Please see Debugging in WordPress for more information. (This message was added in version 3.6.0.) in /var/www/html/7awi/wp-includes/functions.php on line 5865.

I don’t have any custom functions or custom plugins and everything is up to date and I’ve disabled all the cron jobs to make sure that the recurring of the error at same time every week is not caused by a cron.
how to know if it’s a plugin or apache setting and why a notice is taking my website down while it’s not an error? and the PHP debug log is not really helping me finding the cause

Why is text2wav not working in phpagi demo

I’m just trying to run demo in PHPAGI folder available here: https://sourceforge.net/projects/phpagi/files/phpagi/2.20/

However, the text2wav is not working. When the script has to run text2wav (in dtmf.php for example), this error show:

ast_openstream_full: File /var/spool/asterisk//tmp//text2wav_f87b365372c500c76e497087ac7e470a does not exist in any format

I tried a lot of things: giving permission for every file, trying to understang text2wav source code (https://phpagi.sourceforge.net/phpagi22/api-docs/__filesource/fsource_phpAGI__phpagi.php.html#a1331), I put the max verbosity in asterisk console and activated agi debug on but still can’t understnand what’s happening. the fact is, the file in /var/spool/asterisk//tmp//text2wav_f87b365372c500c76e497087ac7e470a do exist in txt format but not in wav

Is it possible to join “with” query when i use model oriented request

I have a query that i’m writed to fetch data

with last_sent_at as (
    Select offer_id, lead_id, max(created_at) as sent_at
    From offer_history
    Group by offer_id, lead_id)

I need to join it with laravel model system.
So i have three tables: leads => history => offers
I have request
Lead::with([..., 'offers'])->someFunction(?)->filters()->get();

And i need to fetch data from ‘last_sent_at’ but i dont understand how to do it.
Im tried subQuery, but it works wert slow

Doctrine set Collection via join table which is now an entity

I’m working on an old project where we have an entity that had a may to many collection via a join table :


class Company
{
    private Collection $contacts;

    public function getContacts(): Collection
    {
        return $this->contacts;
    }

    public function setContacts(Collection $contacts):void
    {
        $this->contacts = $contacts;
    }
}

However, over time, the join table has become an entity of its own, so now as well as a Contact entity, we now have a CompanyContact entity. I’m refactoring the class to incorporate this change, but I’m not sure about the setContacts method. Here’s what I have now:

class Company
{
    private Collection $companyContacts;

    public function getCompanyContacts(): Collection
    {
        return $this->companyContacts;
    }

    public function setCompanyContacts(Collection $companyContacts):void
    {
        $this->companyContacts = $companyContacts;
    }

    public function getContacts(): Collection
    {
        return $this->companyContacts->map(function (CompanyContact $compayContact) {
            return $companyContact->getContact();
        });
    }

    // How should I write this method ???
    public function setContacts(Collection $contacts):void
    {
        $this->contacts = $contacts;
    }
}

I’m not sure how to set this. Should I be checking through the existing $companyContacts and adding/removing where necessary, or creating a new Collection? We want to preserve the old methods somehow.
The first method seems to be more correct than ditching the old collection and creating a new one, since that would mean losing the additional CompanyContact column data, so I’m a little bit stumped here, can anyone assist? Many thanks!

Display of page content bypassing the login page (PHP) [closed]

I have created two pages: a login page and a data display page. The login page checks if the user’s credentials (email and password) exist in the database, and if valid, it redirects the user to the second page. The issue I’m facing is that if someone directly types the URL of the second page into their browser (e.g., http://localhost/fileproject/secondpage.php), the page loads normally without any requirement for login. How can I prevent direct access to the second page without logging in first?

I tried to solve this issue by using PHP sessions. When a user logs in, I store the UserID in the PHP session (using the command $_SESSION[‘UserID’]). On the page that displays the data (i.e., the secondpage), I check whether $_SESSION[‘UserID’] is set. If it is not, then I redirect the user to the login page (admin.php).

Here’s a simplified version of my login page code:

<?php include 'db.php'; session_start(); $conn->set_charset("utf8mb4");

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $email = $_POST['email'];
    $password = $_POST['password'];

    $sql = "SELECT * FROM Users WHERE Email = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("s", $email);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows == 1) {
        $row = $result->fetch_assoc();
        $passwordHash = $row['PasswordHash'];

        if (password_verify($password, $passwordHash)) {
            $_SESSION['UserID'] = $row['UserID'];
            header("Location: cmsexotic.php");
            exit();
        } else {
            echo "Wrong combination of email and password.";
        }
    } else {
        echo "Wrong combination of email and password.";
    } } ?>

On my second page, I have the following code at the top to check the session:

<?php
session_start();

if (!isset($_SESSION['UserID'])) {
    header('Location: admin.php');
    exit();
}
?>

Despite this, direct access to the page is still possible. I’ve tried using PHP sessions. When a user logs in, I store the UserID in the PHP session ($_SESSION[‘UserID’]). On the data display page, I check if $_SESSION[‘UserID’] is set and if it is not, then I redirect the user to the login page (admin.php).

I’m not sure why this isn’t working, so I would appreciate any help or suggestions.

true, if given variable is matching all element/column in given array ( Multidimensional ) in php

Below is my array :

$my_value_is = Array ( [2] => Array ( [id] => 2 [price] => 23) [50] => Array ( [id] => 50 [price] => 56 ) )

$my_var = 56;

I need it to return true if all columns ( price ) match that given variable value; otherwise, it should return false.

hence as per my $my_var, i should get result as false, because id:2 has price:23 which is not matching.

I tried in_array function, but that wont work :

$u_in_array = in_array($my_var, array_column($my_value_is , 'price'));
if($u_in_array ) {
    echo 'value is true';
 } else {
    echo 'value is false';
 }

but it giving me as value is true , where as i need value is false.

Access API on server on Laravel, Web work but when access with API get error 404

My Directory
public_html/mobile/ <– Laravel install File, which fokus on API.

There are other code in the public_html, which currently I did to make for the Web.

On Localhost
When test with Localhost everything work fine with .htaccess, but if I delete .htaccess, the API fail to work.

On Server
If got .htacess in public_html/mobile/public the Laravel fail to run
I delete the .htaccess in public_html/mobile/public, it manage to run the Laravel welcome pages. When I try to call the API I get “error 404”

PHP Warning: Message: strpos(): Empty needle

I was running a PHP test development server on localhost and I stumbled across this warning that breaks the site entirely, the error is

PHP Warning: Message: strpos(): Empty needle

and the snippet causing this error is

if ($CI->config->item('csrf_protection') === TRUE AND ! (strpos($action, $CI->config->base_url()) === FALSE OR strpos($form, 'method="get"')))

I tried googling for the error but none gave me a solid answer about it.