Eloquent hasOneThrough relation

Currently my database setup looks like this:

Users table (User model):

  • id,
  • email

Discounts table (Coupon model)

  • code
  • amount

Now, I decided to create a pivot table, where I will store a discount value for a user. One user will have a single discount value. For this, I created PractitionerVoucher model with this table setup:

  • voucher_id
  • practitioner_id

Upon creating a Coupon record, I save the coupon_id (voucher_id in this case) and the user_id (practitioner_id in this case) values to PractitionerVoucher table. Now, my question is, how do I get the User record from the Coupon model? For example:

$coupon = Coupon::first();
$coupon->practitioner;

I tried to create hasOneThrough relation on Coupon model, but no luck so far. This is what I tried:

public function practitioner(){
  return $this->hasOneThrough(User::class, PractitionerVoucher::class, 'practitioner_id', 'id');
}

Using this relation, I get no query results for the User model. This is how my database records look like:

Coupons table
enter image description here

PractitionerVoucher table:
enter image description here

What am I doing wrong here? Any help is appreciated.

How to import multiple excel files in Laravel using Laravel Excel?

I am trying to import multiple files in Laravel using Laravel Excel.

I have the following code in my blade file, which allows me to select multiple files to be uploaded:

<form action="{{ route('file-import') }}" method="POST" enctype="multipart/form-data">
    @csrf
    <div class="form-group mb-4" style="max-width: 500px; margin: 0 auto;">
        <div class="custom-file text-left">
            <input type="file" name="file" class="custom-file-input" id="customFile" multiple>
            <label class="custom-file-label" for="customFile">Choose file</label>
        </div>
    </div>
    <button class="btn btn-primary">Import data</button>
</form>

In the controller I use the following code:

    public function fileImport(Request $request) 
    {   
        
        Excel::import(new LogsImport, $request->file('file')->store('temp'));
        return back();
    }

It works fine but it only imports the first file I select.
I believe I need some kind of foreach statement. I tried the following option:

public function fileImport(Request $request) 
    {   
        foreach($request->file('file') as $f){
            Excel::import(new LogsImport, $f->store('temp'));
        }
        return back();
    }

But using this no file is getting imported.

I also tried printing $request but I get a huge array and I can’t find anything relevant that points to the files I uploaded.

Any help would be appreciated. Thanks

This is the correct form to do a class with construct in php?

This is the creation of the class
Its about an example using the name dog but im working on some aplication and i will change this data for something diferent next days, if you could help me and told me if its ok i will apreciate it.

class Dog extends Connection
{
    private $dogId;
    private $name;
    private $albumId;
    private $mediaTypeId;
    private $genreId;
    private $composer;
    private $miliseconds;
    private $bytes;
    private $unitPrice;


    public function __construct($_dogId, $_name, $_albumId, $_mediaTypeId, $_genreId, $_composer, $_miliseconds, $_bytes, $_unitPrice)
    {
        $this->dogId = $_dogId;
        $this->name = $_name;
        $this->albumId = $_albumId;
        $this->mediaTypeId = $_mediaTypeId;

        $this->genreId = $_genreId;
        $this->composer = $_composer;
        $this->miliseconds = $_miliseconds;
        $this->bytes = $_bytes;
        $this->unitPrice = $_unitPrice;
    }

    public function getDogName(){
        return $this->name;
    }

    public function getDogComposer(){
        return $this->composer;
    }

    public function getUnitPrice(){
        return $this->unitPrice;
    }

    public function getDuration(){
    }
    
}```

File Renaming While Uploading In PHP [duplicate]

I am new to PHP and I need some help in the below code. The below code is working fine but I need to add a “Functionality to be added in the below code, so that if any New File is uploaded it should auto increment in a series. For Example: 00004001, 00004002, 00004003…. and so on.

Please help…! Below is the existing code. Currently it Uploads the exact file name to the remote server.

<?php
if ( empty( $_FILES['file'] ) ) {
    return;
}
$ftp_server = "xx.xx.x.xxxx";
$ftp_user_name = "xxxxxxx";
$ftp_user_pass = "xxxxxxxxxxxxxxxxxxxxxxxxxx";
$destination_file = "";
$source_file = $_FILES['file']['tmp_name'];

// set up basic connection
$conn_id = ftp_connect($ftp_server);


// login with username and password
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass); 

//ftp_pasv($conn_id, true); 

// check connection
if ((!$conn_id) || (!$login_result)) { 
    echo "FTP connection has failed!";
    echo "Attempted to connect to $ftp_server for user $ftp_user_name"; 
    exit; 
}   else {
    
    
    echo "<p align=center> Your Image has been Uploaded if you dont't see any Error Msg Below</p> ";
}

// upload the file

$destination_folder = "/";
$destination_file = $destination_folder . "/" . basename($_FILES['file']['name']);
//ftp_put($conn_id, $destination_file, $source_file, FTP_BINARY); 
$upload = ftp_put($conn_id, $destination_file, $source_file, FTP_BINARY); 

// check upload status
if (!$upload) { 


echo "<p align=center> **File Upload Has Failed &#128558</p> ";

} else {
echo "";
}

// close the FTP stream 
ftp_close($conn_id);
?>

WhereIn condition with UUID not working in Laravel

public function skills($id)
    { 
        $skills = DB::table("industry_skill_sets")
                    ->whereIn('industry_id', [$id])
                    ->pluck("name","id");
                    print_r($skills); exit;
    }

Here id is UUID seperated by comma. When I echo Id I am getting

2b5e5507-7e01-45fe-b0ed-331135479061,7c816e0f-d6e2-489c-bdce-df064b3e99f9

When I use this variable in WhereIn condition , It shows error

SQLSTATE[22P02]: Invalid text representation: 7 ERROR: invalid input
syntax for type uuid:
“2b5e5507-7e01-45fe-b0ed-331135479061,7c816e0f-d6e2-489c-bdce-df064b3e99f9”

I am using PostgreSQL as database

Laravel 7: Finding a relation between two dates

I’m trying to get the jobs relation between two dates by using the whereHas method however I keep getting an Integrity constraint violation and am not sure what is causing this issue.

I’ve tried using the with and where method, but they all return the same error.

Error:

SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'created_at' in where clause
is ambiguous (SQL: select * from `categories` where exists (select * from `jobs` inner
join `category_job` on `jobs`.`id` = `category_job`.`job_id` where `categories`.`id` = `category_job`.`category_id` and `created_at` = `=<` and `created_at` >= `2022-06-19 23:59:59`))

Function:

    /**
     *
     */
    public function categoriesThisWeek()
    {
        $categoriesThisWeek = Category::with('jobs')
            ->whereHas("jobs", function ($query) {
                $query
                    ->whereColumn('created_at', '=<', Carbon::now()->startOfWeek())
                    ->whereColumn('created_at', '>=', Carbon::now()->endOfWeek());
            });

        return  $categoriesThisWeek->get();
    }

webhost000 cannot insert data to database [duplicate]

I’m using webhoost000 to insert certain data but every time I try it returns the error message. I tried making a select statement and it works, I also try to use my query to the phpmyadmid and it also work i don’t understand why my code is not working
enter image description here

$dbServername = "localhost";
$dbUsername = "id1911627_users";
$dbPassword = "MC{aJpz1_174]MTU";
$dbName = "id1911627_usersdata";

$conn = mysqli_connect($dbServername, $dbUsername, $dbPassword, $dbName);

if(!$conn){
    die("connection failed: ".mysqli_connect_error());
}

$db = "id1911627_usersdata";
$dbs = mysqli_select_db($conn, $db);

if(!$dbs){
    die("connection failed: ".mysqli_connect_error());
}

$un = $_GET['u'];
$pw = $_GET['p'];
$fn = $_GET['f'];
$age = $_GET['a'];
$gdr = $_GET['g'];

$sql = "INSERT INTO usersdata (username, password, fullname, age, gender, height, weight, bloodpreasure, sugarlvl) VALUES ('$un', '$pw', '$fn', '$age', '$gdr', '0', '0', '0', '0')";
$query = mysqli_query($conn, $sql);

if($query){
    echo "added";
}
else{
    echo "not ".$sql;
}

How to get base URL of index file in PHP after htaccess redirect that doesn’t change the URL

I have this in my htaccess:

RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]

and I have a PHP script that is redirecting to two directories /game/ or block/ I want to use curl to open files in one of the directories.

This is my code for getting the URL:

function is_https() {
    // apache
    if (isset($_SERVER['HTTPS'])) {
        return true;
    }
    // heroku
    if (isset($_SERVER['HTTP_X_FORWARDED_PORT']) && isset($_SERVER['HTTP_X_FORWARDED_PROTO'])) {
        return $_SERVER['HTTP_X_FORWARDED_PORT'] == 443 || $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https';
    }
    return false;
}

function get_self() {
    return 'http' . (is_https() ? 's' : '') . '://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
}

function main() {

    $addresses = json_decode(file_get_contents('ip.json'));
    $url = get_self() . (in_array($_SERVER['REMOTE_ADDR'], $addresses) ? "/block/" : "/game/");
    $url .= $_GET['q'];
    
    echo $url;
}

if (isset($_GET['q'])) {
    main();
}

The problem is that when I access the file locally for testing when I try to access:

http://localhost/~kuba/jcubic/support/order/app/index.js

It got this URL:

http://localhost/~kuba/jcubic/support/order/app/index.js/game/index.js

how can I get the URL of the index.php the path where the .htaccess file is located?

I one this to work as the root directory https://example.com/ the same as in any directory.

How to conver PHP foreach to JavaScript

I have the following php (old application) and I want to recreate a robots.txt for a Nuxt Application in in valid JS:

//Disallow all for container domains /
$is_container = false;
$containers = array('url.one','url.two');
foreach($containers as $container) {
    if(strpos($_SERVER['HTTP_HOST'], $container) !== false) {
        $is_container = true;
    }
}

if($is_container) {
?>
User-agent: *
Disallow: /

<?php
exit;
}

in my Nuxt.config I have this option:

// doSomthing: Is where I want to create the conditional logic above

  robots: (doSomething) => {
    return {
      UserAgent: '*',
      Disallow: '/',
    }
  },

Please could you help me in the right direction?

How can i display json data webhook response into html body from ngrok

i am using ngrok for receiving webhook response in json data format via localhost. everything is working fine webhook response also showing in ngrok portal. but i want to show webhook response in html body instead of ngrok portal.

i attached images for each step please let me know how can i fix this.enter image description here

enter image description here

enter image description here

Website hacked – not possible delete .htaccess – automatic rewrite with deny all [closed]

Today I check and looks like my website WP hacked.

Very stranges files available in public_html like fcasd.php or simmilar to wp files example: original file wp is plugin-install.php and I see file plugins-installs.php – with hacked code. this is not original wp file.

I delete all this files, bus still in all my website I have access denied.

I check .htaccess and I see:

<FilesMatch ".(py|exe|php)$">
 Order allow,deny
 Deny from all
</FilesMatch>
<FilesMatch "^(about.php|radio.php|index.php|content.php|lock360.php|admin.php|wp-login.php|wp-l0gin.php|wp-theme.php|wp-scripts.php|wp-editor.php)$">
 Order allow,deny
 Allow from all
</FilesMatch>
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

This is not my code. I try delete this file and change content, but everytime this code is rewrite.

Can anyone help me?

Auto submitting a demand with if condition [closed]

I am really unsure if this is possible, but I want to know the best possible way around, we have a website wherein stock is updated in a particular time every day and we have to get the stock as soon as it is uploaded due to huge demand, we have been unsuccessful at booking the stock multiple times which directly effects our business. The website I think works on java language and uses php as well.

I am unable to right click and the page does not auto refresh, the way we refresh is by toggling through the drop down list, once the stock is updated we are able to see the new quantity and book accordingly.

So the issue that I need to resolve is, is there a way to automate the toggling through the drop down and hit the submit button as soon as the stock is refreshed with x quantity?

Thanks in advance.

How do resolve this issue?

I’m building a web based chat application. Which involves users sign up and login.

Each signed up user has a unique_id Which is used to identify different users across all pages in the app.

I have these tables in MySQL database.users, messages, pinned_user.
In the the messages table I have msg_id(int),sent_by_id(using the users unique_id), sent_to_id(using the users Unique_id), msg_time(current_timestamp), message (the sent or received message).

In the pinned_user table
I have pin_id, pinned(using the users unique_id), pinned_by(using users unique_id), action(determines if a user is pinned or unpinned).

You can only chat with someone if the both of you pinned each other.

I want to order the pinned_users according to newest sent or received messages for different users in each session.
Here is my code.

$pinned_users = mysqli_query($conn, "SELECT * FROM pinned_user LEFT JOIN users ON users.unique_id = pinned_user.pinned LEFT JOIN messages ON messages.sent_by_id = pinned_user.pinned AND messages.sent_to_id = pinned_user.pinned_by WHERE pinned_user.pinned_by = $_SESSION["unique_id"] AND action = 'unpin' ORDER BY messages.msg_time DESC ");

My problem is that the pinned_users are outputted according to the number of times their sent_by_id appears in the messages table.

Any solution to this?.

How to input to database after i append input field? the value always empty or 0

I append input field when click the add barcode button and i want to passing value to my controller and assign to my database but the value always 0 or ” how to assign to my database ?

when i call input name its produce empty value no actual input that we submited

Here my code

<form method="POST" action="<?php echo base_url('cabang/updatedatacabang') ?>" >
 <tr height='30px;'>
                <td>NO BARCODE APAR</td>
                <td align='center'>:</td>
                <td Colspan='2' width='10%'><input type="text" style="height:22px; width:160px; display:block; border:solid 1px #ADA3A3; border-radius:3px;" name="barcodeapar" title="barcode" AUTOCOMPLETE=OFF required></input></td>
                </td>
                <td>
                    <button onclick="add()">add Barcode</button>
                    <button onclick="remove()">remove Barcode</button>
                </td>
                
            </tr>
</form>

This what i append :

function add() {
  var new_chq_no = parseInt($('#total_chq').val()) + 1;
  var new_input = " <tr height='30px;' id='titik"+ new_chq_no + "'> <td width='60%' id='titik" + new_chq_no + "' > NO BARCODE APAR" + new_chq_no + "</td> <td align='center' id='titik" + new_chq_no + "'> : </td> <td Colspan='2' id='titik" + new_chq_no + "'> <input style='height:22px; width:160px; display:block; border:solid 1px #ADA3A3; border-radius:3px;' type='text' name='new_" + new_chq_no + "'  id='new_" + new_chq_no + "'  required> </td> </tr> ";
  var last_chq_no = $('#total_chq').val();
  
  
  
  if (last_chq_no < 5){    
  $('#new_chq').append(new_input);
  $('#total_chq').val(new_chq_no);
  }
   
}
      </script>

PHP unlink() files after it is added to ZipArchive

I am adding multiple files to a ZipArchive each file has a unique name.

Controller:

$zip = new ZipArchive();
$zip->open($zipPath, ZipArchive::CREATE | ZipArchive::OVERWRITE);
$filesToClose = $this->advancedService->addFiles($files, $zip);
$zip->close();

foreach ($filesToClose as $file) {
    fclose($file);
    unlink(stream_get_meta_data($file)['uri']);
}
// return response

Service:

// addFiles function
foreach ($files as $file) {
    $fileName = 'FILE_'.$file->getId().'.'.$file->getExtension();

    $tempFile = tmpfile();
    $content = file_get_contents('uriFromSdk');
    fwrite($tempFile, $content);
    $zipArchive->addFile(stream_get_meta_data($tempFile)['uri'], $fileName);

    $filesToClose[] = $tempFile;
}

return $filesToClose;

In controller I get this error:

stream_get_meta_data(): supplied resource is not a valid stream resource

The main problem is I can not close or delete any file before $zip->close(), How can I unlink the files from the server ?

Keep in mind fclose() doesn’t throw this error, only the stream_get_meta_data().

Thanks.