How to print preview and save in one button in laravel

Is there a way how to add two function which is the print and move the data to another table in a one button? In my project where I have table which is the accepted reservation table. Here the admin can let borrow the equipment since it is accepted reservation. So when I click the borrow button how can I print preview the row data and move that row data in borrowed item since it is now a borrowed item. Anyone can help me?

Please refer to this image

Here when I click the borrow button the print preview will display only the row data and move the row data to borroweditem table. While the quantity of that item which is in another table will be deducted by 1.

Here’s my view.blade.php

<div class="card shadow mb-4">
    <div class="card-header py-3">
    <h6 class="m-0 font-weight-bold text-primary">Accepted Reservations</h6>
    </div>
    <div class="card-body">

    <div class="table-responsive">
     <table class="table table-bordered tbl_acceptres display" id="dataTable" width="100%" cellspacing="0">
     <thead>
<tr>
<th hidden>Id</th>
<th>Name</th>
<th>Equipment</th>
<th>Reservation Date</th>
<th>Rooms</th>
<th>Action</th>
</tr>
</thead>
<tbody>
 @foreach ($acc as $accdata)

<tr>
 <td hidden> </td>
<td>{{ $accdata->name }} </td>
<td>{{ $accdata->Name_item }}</td>
<td>{{ $accdata->dt_item }}</td>
<td>{{ $accdata->room_item }} </td>
<td>
<form action="{{route('admin.reservation.borrow',$accdata->id)}}" method="POST">
{{ csrf_field() }}
<button type="submit" class="btn btn-primary btn-sm">Borrow <i class="fas fa-chevron-right"></i></button>
</form>
</td>
</tr>

@endforeach
</tbody>
</table>
</div>
</div>

Here’s my controller

public function borrow(Request $request, $id){

$bor = Reservation::where('id', $id)->first();
$kl=$first->name;
$mn=$first->Name_item;
$op=$first->dt_item;
$qr=$first->room_item;

$bitem = new BorrowedItem();
$bitem->bname= $kl;
$bitem->bdate= $mn;
$bitem->itemb= $op;
$bitem->broom= $qr;

$bitem->save();
$bor->delete();

returned redirect()->back()->with('message','Successfully borrowed item')

}

supervisor , php7.4-fpm entered RUNNING state

I have configured supervisor with php7.4-fpm and I got these logs , it always restart

2022-02-06T10:23:08.501156489Z 2022-02-06 10:23:08,500 INFO success: php7.4-fpm entered 
RUNNING state, process has stayed up for > than 0 seconds (startsecs)
2022-02-06T10:23:08.501390216Z 2022-02-06 10:23:08,501 INFO exited: php7.4-fpm (exit status 0; 
expected)
2022-02-06T10:23:08.985646043Z 2022-02-06 10:23:08,985 INFO spawned: 'php7.4-fpm' with pid 545
2022-02-06T10:23:09.001912738Z 2022-02-06 10:23:09,001 INFO success: php7.4-fpm entered 
RUNNING state, process has stayed up for > than 0 seconds (startsecs)
2022-02-06T10:23:09.002241911Z 2022-02-06 10:23:09,002 INFO exited: php7.4-fpm (exit status 0; 
expected)

this is my supervisor configuration

[supervisord]
nodaemon = true
logfile = /dev/null
logfile_maxbytes = 0
pidfile = /var/run/supervisord.pid
user=root

[program:php7.4-fpm]
command = /etc/init.d/php7.4-fpm start
stdout_logfile = /dev/stdout
stdout_logfile_maxbytes=0
startsecs = 0
exitcodes= 0
autorestart = true
stderr_logfile = /dev/stderr
stderr_logfile_maxbytes=0
user = root
autostart = true
priority = 5

How to set php.ini path

I installed xampp to work on php projects, and I’m sure I installed it the same as in the course, but when I try to run a Development Server by running php -S localhost:8080, it replies with

Fatal error: Uncaught PDOException: could not find driver in C:xampphtdocsphp-crash-course-202014_product_crud2_betterpublicproductsindex.php:3 Stack trace: #0 C:xampphtdocsphp-crash-course-202014_product_crud2_betterpublicproductsindex.php(3): PDO->__construct(‘mysql:host=loca…’, ‘root’, ”) #1 {main} thrown in C:xampphtdocsphp-crash-course-202014_product_crud2_betterpublicproductsindex.php on line 3

I have done a lot of research and I think the problem is that there is no path to php.ini.
In php.ini I uncommented the extension pdo_mysql but that didn’t work, so on the command line, I typed php --ini and it replied with

Configuration File (php.ini) Path:    
Loaded Configuration File: (none)   
Scan for additional .ini files in: (none)   
Additional .ini files parsed: (none)

I have found the php.ini file in C:/xampp/php/php.ini which from my research should be the right place, so I think I need to set a path for xampp to find php.ini, but I can’t find how.
Is there a command to set a path for php.ini?

check if query builder already issued where or like?

I am so convenient using built-in codedigniter query builder.

I have to output searching to an existing page since that page involves multi-table.
Currently, I already have a lot of if there, I am curious how to check if statement db->where() or db->like() have been called or not.

I am already stuck here, and I am aware that the db->get() will erase the data filtering.
Any suggestion?

How to remove the shipping fee from the refund WooCommerce email template [duplicate]

I want to remove the shipping fee from the refund email template from WooCommerce and the total amount to be without the shipping fee.

<?php

defined( 'ABSPATH' ) || exit;

do_action( 'woocommerce_email_header', $email_heading, $email ); ?>

<?php /* translators: %s: Customer first name */ ?>
<p><?php printf( esc_html__( 'Hi %s,', 'woocommerce' ), esc_html( $order->get_billing_first_name() ) ); ?></p>

<p>
<?php
if ( $partial_refund ) {
    /* translators: %s: Site title */
    printf( esc_html__( 'Your order on %s has been partially refunded. There are more details below for your reference:', 'woocommerce' ), wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES ) ); // phpcs:ignore WordPress.XSS.EscapeOutput.OutputNotEscaped
} else {
    /* translators: %s: Site title */
    printf( esc_html__( 'Your order on %s has been refunded. There are more details below for your reference:', 'woocommerce' ), wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES ) ); // phpcs:ignore WordPress.XSS.EscapeOutput.OutputNotEscaped
}
?>
</p>
<?php


do_action( 'woocommerce_email_order_details', $order, $sent_to_admin, $plain_text, $email );


do_action( 'woocommerce_email_order_meta', $order, $sent_to_admin, $plain_text, $email );


do_action( 'woocommerce_email_customer_details', $order, $sent_to_admin, $plain_text, $email );


if ( $additional_content ) {
    echo wp_kses_post( wpautop( wptexturize( $additional_content ) ) );
}


do_action( 'woocommerce_email_footer', $email );

enter image description here

PHP shell_exec – some shell commands not available

before starting – I have seen some SO similar questions, but tbh I got even more lost.

I am trying to run nvm use and nvm -v within the PHP shell_execute, but am constantly getting the following error:

sh: nvm: command not found

It seems like PHP is using Bourne shell where nvm is not available.
I am mostly using Bash in Terminal where everything is fine (in other shells like ZSH I get the same error).

Questions:

How can I make PHP run commands with shell_exec (if there is alternative I am open for considering it) I usually use in Bash?

Extra notes (maybe helpful):

  1. This command is only used on a local environment so changing settings on dev machine is something I am open to consider. (would be good to support Mac/Win and Linux, but Mac is the main focus at the moment).

  2. If I run which nvm in the bash I get nothing in the terminal.

  3. NVM was installed with Brew (don’t know if that has any impact)

The usecase:

I am building a WP CLI toolkit where one of the commands is wp custom install. The command should switch to the right Node.js version of the project, install npm and php dependencies as well as some extra things.

// basic code sample
namespace Custom/CustomCli;

class CustomCli {

    public static function init(){
    
        if( !(defined('WP_CLI') && WP_CLI) ) return;
        WP_CLI::add_command( 'custom', 'CustomCustomCli' );

    }
    
    /*
    * If the Node.js version !== to .nvmrc try 'nvm use'
    * after correct version is selected run 'npm install'
    * also run 'composer install' and 'composer dump-autoload'
    */
    public function install( $args ){
        WP_CLI::log( shell_exec('nvm -v') ); # once I figure out this I guess I'll know how to fully handle installation
    }

}

CustomCli::init();

WordPress website suddenly gives an error

My WordPress website suddenly stopped working.
I suspect that an automatic update went wrong.

I get the following error:

Warning: Undefined array key 0 in /…/wp-includes/plugin.php on line 957
Warning: Undefined array key 0 in /…/wp-includes/plugin.php on line 960

This is the snippet:

function _wp_filter_build_unique_id( $hook_name, $callback, $priority ) {
if ( is_string( $callback ) ) {
    return $callback;
}

if ( is_object( $callback ) ) {
    // Closures are currently implemented as objects.
    $callback = array( $callback, '' );
} else {
    $callback = (array) $callback;
}

if ( is_object( $callback[0] ) ) {
    // Object class calling.
    return spl_object_hash( $callback[0] ) . $callback[1];
} elseif ( is_string( $callback[0] ) ) {
    // Static calling.
    return $callback[0] . '::' . $callback[1];
}

}

Can someone help me?
This website contains an inventory in woo commerce and the auto-back-up failed.

How to get all results of a table with Many To Many relationship

I’m working on an Online Store project and I wanted to create Add To Favourite system for users to add products that they like to their favourite list.

So I have created a table named favourite_products which goes like this:

enter image description here

So the usr_id stands for user id and prd_id stands for product id.

Now I wanted to get all the data from this table.

So I tried adding this to the Controller:

$userFavourites = new User();
dd($userFavourites->favourites);

But it does not return data and shows this empty collection:

IlluminateDatabaseEloquentCollection {#2862 ▼
  #items: []
}

However data already exists there.

So my question is, how can I show all the results from favourite_products at a table with User Many To Many relationship?

Here is the User.php Model:

public function favourites()
    {
        return $this->belongsToMany(Product::class, 'favourite_products', 'usr_id', 'prd_id')->withTimestamps();
    }

And this the Product.php Model:

public function favouritees()
    {
        return $this->belongsToMany(User::class, 'favourite_products', 'prd_id', 'usr_id');
    }

Ajax form submit with rich text box without page reload

Hello Everyone please I’m having a problem with my ajax form submit. When I use a rich textbox to submit my form I have to click on the submit button twice before the request sends. Please guys I seriously need help. I want that immediately I press the submit button once the form should submit immediately.
Here is my code :

<script src="https://cdn.tiny.cloud/1/qagffr3pkuv17a8on1afax661irst1hbr4e6tbv888sz91jc/tinymce/5/tinymce.min.js" referrerpolicy="origin"></script>

                    <div id="comments">
                        <h5>Comments</h5>
                        <hr style="margin: 15px 0;">
                        <form action="javascript:void(0)" name="comment-form" id="comment-form" method="post">
                            @csrf
                            <textarea id="mytextarea" class="form-control" name="comment" placeholder="Write your Comments Here"></textarea>
                            <small class="text-danger"><strong>Should not exceed 255 characters</strong></small>
                            <input type="hidden" name="banner_id" value="{{$banner->id}}">
                            <input type="hidden" name="user_id" value="{{$usercom}}">
                            <br>
                            <button type="submit" class="btn btn-success btn-sm">Post Comment</button>
                          </form>
                          <div id="comment-loading">
                              <small><b>Please wait</b></small>
                             <img src="{{asset('load-img/loader.gif')}}" alt="" width="50px">
                          </div>
                          <br>

                        <div class="fb-comments" data-href="#" data-width="100%" data-numposts="10" id="div2">
                            <h5 style="margin-left: 10px">{{$banner->comments}} Comments</h5>
                            <hr>
                            <ul class="element" data-config='{ "type": "list", "limit": 5, "element": "li", "more": "↓ show more", "less": "↑ show less", "number": true }' style="list-style-type: none; padding-inline-start: 10px !important;">
                           @forelse ($comments as $comment)
                           <li>
                           <p class="text-success" style="line-height: 1em;"><b>{{$comment->user->username ?? 'Unknown'}}</b></p>
                           <span style="font-size: 14px;">{!!$comment->comment!!}</span>
                        </li>
                           @empty
                               No Comment has been made yet.
                           @endforelse
                        </ul>
                        </div>
                    </div>

<script src="{{asset('js/jquery.min.js')}}"></script>
<script src="{{asset('js/jquery.validate.min.js')}}"></script>
<script>
        if ($("#comment-form").length > 0) {
            $("#comment-form").validate({
                rules: {
      banner_id: {
        required: true,
        maxlength: 11
      },
      comment: {
        required: true,
        maxlength: 255
      },
    },
    messages: {
        banner_id: {
            required: "<small class='text-danger'>Banner Id Required</small>",
        maxlength: "<small class='text-danger'>Your banner id maxlength should be 11 characters long.</small>"
      }, 
      comment: {
            required: "<small class='text-danger'>Comment is Required</small>",
        maxlength: "<small class='text-danger'>Your comment maxlength should be 255 characters long.</small>"
      }, 
    },
         submitHandler: function(form) {
             $.ajaxSetup({
             headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
             }
            });
            $('#comment-loading').show();
             $.ajax({
               url: "{{url('postcomment')}}",
               type: "POST",
               data: $('#comment-form').serialize(),
               success: function( response ) {
                $('#comment-loading').hide();
                document.getElementById("comment-form").reset();     
                   $("#div").load(" #div > *");
                   $("#div2").load(" #div2 > *");             
               }
             });
            }
        })
    }
    </script>

<script>
    tinymce.init({
      selector: "#mytextarea",
      plugins: "emoticons",
      toolbar: "emoticons",
      toolbar_location: "bottom",
      menubar: false
    });
  </script>
<script>
    $(function () {
        $('#comment-loading').hide();
    });
</script>

PLease I seriously need your assistance here. Thanks In advance.

How can i calculate the time user is spending on page?

I have made a function , on login the user actual date month-day-year hours-minutes-second are saved on database .
On log-out i have made a function to calculate the time the user has stayed on page but for some reasons the function is not working.
I need to calculate with the following idea , ‘The time user has logged out’ – ‘The time user has been logged in ‘=’total’,
Then i need to get the all total the user has spent on page and add this total i made the calculation.

 [![public function calculateTimeOnPage(){

        $id = $_SESSION['userid'];
        $stmt = $this->connection->pdo->prepare("SELECT * FROM users WHERE id = '$id'");
        
        $stmt->execute();    
        $result = $stmt->fetch();
        $end_time_on_page = Date("Y-m-d H:i:s");
        $todayDate_ = date('Y-m-d H:i:s');
     
        $total = strtotime($end_time_on_page) - strtotime($result['page_start_time']); 
  
        $actual_date = date("Y-m-d H:i:s",$result['time_on_page']);
    
        $calculate_time_on_page = $total + strtotime($actual_date);
        
        $data = date("Y-m-d H:i:s",$calculate_time_on_page);
        
        echo 'Data : '.$data . '<br>';
        
        $stmt_up = $this->connection->pdo->prepare("UPDATE users SET 
        time_on_page = TIMESTAMPDIFF(SECOND,'".$data."','".$todayDate_."')
        WHERE id = '$id'");

        function convertSecToTime($sec)
        {
            $date1 = new DateTime("@0");
            $date2 = new DateTime("@$sec");
            $interval = date_diff($date1, $date2);
            $parts = ['years' => 'y', 'months' => 'm', 'days' => 'd', 'hours' => 'h', 'minutes' => 'i', 'seconds' => 's'];
            $formatted = [];
            foreach($parts as $i => $part)
            {
                $value = $interval->$part;
                if ($value !== 0)
                {
                    if ($value == 1){
                        $i = substr($i, 0, -1);
                    }
                    $formatted[] = "$value $i";
                }
            }

            if (count($formatted) == 1)
            {
                return $formatted[0];
            }
            else
            {
                $str = implode(', ', array_slice($formatted, 0, -1));
                $str.= ' and ' . $formatted[count($formatted) - 1];
                return $str;
            }
        }

        //convertSecToTime($sec);

        echo convertSecToTime($result['time_on_page']); // qekjo perdoret per mi show sa kohe ka

        echo "UPDATE users SET 
        time_on_page = TIMESTAMPDIFF(SECOND,'".$data."','".$todayDate_."')
        WHERE id = '$id'";

        $stmt_up->execute();
    }][1]][1]

PHP hex2bin acsii table

I try convert hex “fc” to symbol “ü”. Like on this Site. But in php this symbol “ü” not “fc” its like unicode “c3bc”. So how to convert “fc” to symbol “ü” in php ?

Sending scheduled emails with lumen 8 and mailgun

I have a Lumen app (v8) configured for sending emails using Mailgun. Everything works flawlessly when I send the mail immediately, but when I try to use the “later” method it seems to be ignored.
This is what I am using:
file app.php

$app->configure('services');
$app->configure('mail');
$app->configure('queue');

$app->alias('mail.manager', IlluminateMailMailManager::class);
$app->alias('mail.manager', IlluminateContractsMailFactory::class);

$app->alias('mailer', IlluminateMailMailer::class);
$app->alias('mailer', IlluminateContractsMailMailer::class);
$app->alias('mailer', IlluminateContractsMailMailQueue::class);

$app->make('queue');

the Onboard3.php mail class:

<?php
namespace AppMail;

use IlluminateBusQueueable;
use IlluminateContractsQueueShouldQueue;
use IlluminateMailMailable;
use IlluminateQueueSerializesModels;
use IlluminateSupportFacadesDB;

class Onboard3 extends Mailable
{
    use Queueable, SerializesModels;

    /**
     * Create a new message instance.
     *
     * @return void
     */
    public $info;

    public function __construct($info)
    {
        $this->info = $info;
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return
            $this->from('[email protected]', 'Sender name')
            ->subject("Subject")
            ->view('emails.users.onboard3')
            ->text('emails.users.onboard3_plain');
    }
}

My controller method:

Mail::to([
    '[email protected]'
])
->later(
    Carbon::now()->addMinutes(10000)
    , new Onboard3($recipient)
);

Prevent a package from including the provider definition of the embedded composer.json

I have a use case where I want to extend a certain package by using my own service provider as well as extending the provided command.

The package has a composer.json definition as follows:

"extra": {
    "laravel": {
      "providers": ["BeyondCode\LaravelWebSockets\WebSocketsServiceProvider"],
      "aliases": {
        "WebSocketRouter": "BeyondCode\LaravelWebSockets\Facades\WebSocketRouter"
      }
    }
  }

I want laravel to ignore the providers definition without modifying the package.

Does anyone know if that is actually possible?

Setup Xdebug configuration for php scripts called in cron by docker-entrypoint.sh in vscode

Currently using VSCode on MacOS, Xdebug is working well for my php web application ran with docker.

But I also have some php scripts that are called by the docker-entrypoint.sh as crons and I’d like to be able to debug them as well. I can’t configure it properly, nothing happens when I set breakpoints while the crons are running.

Here is my launch.json configuration at the moment (all the codesource – web, scripts…- is under myapp/app) :

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Listen for Xdebug",
            "type": "php",
            "request": "launch",
            "port": 9001,
            "log": true,
            "pathMappings": {
                "/opt/myapp/app": "/Users/me/src/myapp/app"
            }
        },
        {
            "name": "Launch currently open script",
            "type": "php",
            "request": "launch",
            "program": "${file}",
            "cwd": "${fileDirname}",
            "port": 9002,
            "log": true
        }
    ]
}

In my docker-compose.yml, I also have PHP_XDEBUG_ENABLED=true for the web container and the cron container of course.

Any ideas / configuration examples to get the debug working for the php crons ?

Laravel 8 – Insert using multiple join and calculation laravel

I want to solve the following problem using one query for example

Questions Table

 id  |  question | correct_answer | point

 1   | "what ..?"| 'test'         | 10
 2   | "what ..?"| 'test'         | 5

Answers Table

id |  question_id | user_id | answers | point


Using Laravel 8 I want to add answers to multiple questions at the same time using join and get scores from the questions table and if user answers match to questions.correct_answer also add its score to answers table
use something like code:

DB::table('questions')->join('answers','answers.question_id','=','questions.id')

Thanks in Advance 🙂