Tuesday, 28 May 2024

Laravel Export data to csv

 use Illuminate\Http\Response;


// Define a function to export data to CSV

function exportToCSV($exportData, $columns)

{

    $filename = "ReportsForm.csv";


    // Set HTTP headers

    $headers = [

        'Content-type' => 'text/csv',

        'Content-Disposition' => "attachment; filename=$filename",

        'Pragma' => 'no-cache',

        'Cache-Control' => 'must-revalidate, post-check=0, pre-check=0',

        'Expires' => '0',

    ];


    // Create a callback function to stream CSV data

    $callback = function () use ($exportData, $columns) {

        $file = fopen('php://output', 'w');

        fputcsv($file, $columns);

        $i = 1;

        foreach ($exportData as $item) {

            $currentData = [

                $i++,

                $item->name,

                $item->email,

                $item->company,

                $item->country,

                $item->hear_from,

                $item->is_subscribed == 0 ? "YES" : "NO",

                $item->created_at,

            ];

            fputcsv($file, $currentData);

        }

        fclose($file);

    };


    // Return a streamed response

    return response()->stream($callback, Response::HTTP_OK, $headers);

}


// Controller method to handle export

public function exportData($id = null)

{

    try {

        if (empty($id)) {

            $exportData = ReportForm::all();

        } else {

            $exportData = ReportForm::whereIn('id', $id)->get();

        }


        // Define columns for CSV

        $columns = ["Index", "Name", "Email", "Company", "Country", "Hear From", "Subscribed", "Date"];


        // Export data to CSV

        return exportToCSV($exportData, $columns);

    } catch (\Exception $e) {

        // Handle exceptions

        return response()->json(['error' => 'Failed to export data.'], Response::HTTP_INTERNAL_SERVER_ERROR);

    }

}


laravel edit existing pdf, and add new page or content

Dependencies: 

composer require setasign/fpdf

composer require setasign/fpdi

composer require barryvdh/laravel-dompdf

Service class :

<?php

namespace App\Services;

use setasign\Fpdi\Fpdi;
use Barryvdh\DomPDF\Facade as PDF;
use Barryvdh\DomPDF\Facade\Pdf as FacadePdf;

class PdfService
{
    public function addHtmlPageToPdf($existingPdfPath, $htmlContent, $outputPdfPath)
    {
        // Load the existing PDF
        $pdf = new Fpdi();
        $pageCount = $pdf->setSourceFile($existingPdfPath);

        // Import all pages from the existing PDF
        for ($pageNo = 1; $pageNo <= $pageCount; $pageNo++) {
            $templateId = $pdf->importPage($pageNo);
            $size = $pdf->getTemplateSize($templateId);

            $pdf->AddPage($size['orientation'], [$size['width'], $size['height']]);
            $pdf->useTemplate($templateId);
        }

        // Convert HTML to PDF using DOMPDF
        $htmlPdfContent = FacadePdf::loadHTML($htmlContent)->output();

        // Create a temporary file for the new PDF page
        $tempHtmlPdfPath = tempnam(sys_get_temp_dir(), 'html_pdf_') . '.pdf';
        file_put_contents($tempHtmlPdfPath, $htmlPdfContent);

        // Add the new HTML page as the last page of the PDF
        $pdf->AddPage();
        $pdf->setSourceFile($tempHtmlPdfPath);
        $templateId = $pdf->importPage(1);
        $pdf->useTemplate($templateId);

        // Output the new PDF
        $pdf->Output($outputPdfPath, 'F');

        // Clean up the temporary file
        unlink($tempHtmlPdfPath);
    }
}



Controller : 

<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Services\PdfService;

class PDFController extends Controller
{
    protected $pdfService;

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

    public function addCodeToPdf(Request $request)
    {
        $existingPdfPath=storage_path('app/reports/example.pdf');
        $htmlContent = '<h1>New Page Content</h1><p>This is a new page.</p>';
        $outputPdfPath = storage_path('app/reports/example.pdf'); //Overwrite existing
        $this->pdfService->addHtmlPageToPdf($existingPdfPath, $htmlContent, $outputPdfPath);
        return response()->download($outputPdfPath);
    }
}



Route : 


use App\Http\Controllers\PdfController;

Route::get('/add-html-page', [PdfController::class, 'addHtmlPage']);

Wednesday, 3 April 2024

Jquery datatable add custom dropdown to table search,

<!doctype html>


<html lang="en">


<head>

  <meta charset="utf-8">


  <title>Add select drop-down filter to DataTable</title>

  <meta name="description" content="">

  <link rel="stylesheet" href="https://cdn.datatables.net/1.10.23/css/jquery.dataTables.min.css" />

  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" />

<style>

  select.form-control{

    display: inline;

    width: 200px;

    margin-left: 25px;

  }

</style>

</head>


<body>

  <div class="container mt-4">

    <!-- Create the drop down filter -->

    <div class="category-filter">

      <select id="categoryFilter" class="form-control">

        <option value="">Show All</option>

        <option value="Classical">Classical</option>

        <option value="Hip Hop">Hip Hop</option>

        <option value="Jazz">Jazz</option>

      </select>

    </div>


    <!-- Set up the datatable -->

    <table class="table" id="filterTable">

      <thead>

        <tr>

          <th scope="col">Artist</th>

          <th scope="col">Category</th>

        </tr>

      </thead>

      <tbody>

        <tr>

          <td scope="col">Public Enemy</td>

          <td scope="col">Hip Hop</td>

        </tr>

        <tr>

          <td scope="col">Chet Baker</td>

          <td scope="col">Jazz</td>

        </tr>

        <tr>

          <td scope="col">Billie Holiday</td>

          <td scope="col">Jazz</td>

        </tr>

        <tr>

          <td scope="col">Vivaldi</td>

          <td scope="col">Classical</td>

        </tr>

        <tr>

          <td scope="col">Jurrasic 5</td>

          <td scope="col">Hip Hop</td>

        </tr>

        <tr>

          <td scope="col">Onyx</td>

          <td scope="col">Hip Hop</td>

        </tr>

        <tr>

          <td scope="col">Tchaikovsky</td>

          <td scope="col">Classical</td>

        </tr>

        <tr>

          <td scope="col">Oscar Peterson</td>

          <td scope="col">Jazz</td>

        </tr>

      </tbody>

    </table>


  </div>


  <script src="https://code.jquery.com/jquery-3.5.1.min.js"

    integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>


  <script src="https://cdn.datatables.net/1.10.23/js/jquery.dataTables.min.js"></script>


  <script>

    $("document").ready(function () {


      $("#filterTable").dataTable({

        "searching": true

      });


      //Get a reference to the new datatable

      var table = $('#filterTable').DataTable();


      //Take the category filter drop down and append it to the datatables_filter div. 

      //You can use this same idea to move the filter anywhere withing the datatable that you want.

      $("#filterTable_filter.dataTables_filter").append($("#categoryFilter"));

      

      //Get the column index for the Category column to be used in the method below ($.fn.dataTable.ext.search.push)

      //This tells datatables what column to filter on when a user selects a value from the dropdown.

      //It's important that the text used here (Category) is the same for used in the header of the column to filter

      var categoryIndex = 0;

      $("#filterTable th").each(function (i) {

        if ($($(this)).html() == "Category") {

          categoryIndex = i; return false;

        }

      });


      //Use the built in datatables API to filter the existing rows by the Category column

      $.fn.dataTable.ext.search.push(

        function (settings, data, dataIndex) {

          var selectedItem = $('#categoryFilter').val()

          var category = data[categoryIndex];

          if (selectedItem === "" || category.includes(selectedItem)) {

            return true;

          }

          return false;

        }

      );


      //Set the change event for the Category Filter dropdown to redraw the datatable each time

      //a user selects a new filter.

      $("#categoryFilter").change(function (e) {

        table.draw();

      });


      table.draw();

    });

  </script>

</body>


</html>

Sunday, 3 March 2024

php send email SMTP

  if (empty($nameErr) && empty($emailErr) && empty($contactNumberErr)) {

        $dotenv = parse_ini_file('.env');
        // Retrieve SMTP server settings and email details from the .env file
        $smtpServer = $dotenv['MAIL_HOST'] ?? null;
        $smtpPort = $dotenv['MAIL_PORT'] ?? null;
        $username = $dotenv['MAIL_USERNAME'] ?? null;
        $password = $dotenv['MAIL_PASSWORD'] ?? null;
        // Email information
        $to = $dotenv['MAIL_SEND_TO']?? null;
        $subject = "Contact Form Submission";
        $headers = "From: " . ($dotenv['MAIL_FROM_NAME'] ?? null) . " <" . ($dotenv['MAIL_FROM_ADDRESS'] ?? null) . ">\r\n";
        $headers .= "MIME-Version: 1.0\r\n";
        $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
        // Email body - format details into a table

        $message='
        <!DOCTYPE html>
        <html lang="en">
       
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>Contact Form Submission</title>
            <style>
                /* Resetting default margin and padding */
                body, h1, p, table {
                    margin: 0;
                    padding: 0;
                }
       
                /* Centering content */
                body {
                    display: flex;
                    justify-content: center;
                    align-items: center;
                    height: 100vh;
                    background: #EDF2F7;
                }
       
                /* Styling main container */
                .v1MsoNormalTable {
                    width: 70%;
                    max-width: 480px;
                    background: white;
                    border-radius: 2px;
                    box-shadow: 0 2px 0 rgba(0, 0, 150, 0.025), 2px 4px 0 rgba(0, 0, 150, 0.015);
                    margin: 0;
                    padding: 24px;
                    box-sizing: border-box;
                }
       
                /* Styling header */
                .v1MsoNormalTable h1 {
                    font-size: 13.5pt;
                    color: #3D4852;
                    margin-bottom: 10px;
                }
       
                /* Styling paragraphs */
                .v1MsoNormalTable p {
                    font-size: 11.5pt;
                    color: #74787E;
                    line-height: 18px;
                }
       
                /* Styling table */
                .v1MsoNormalTable table {
                    width: 100%;
                    border-collapse: collapse;
                    margin-bottom: 10px;
                }
       
                /* Styling table cells */
                .v1MsoNormalTable td {
                    padding: 7.5pt;
                    border-bottom: 1px solid #EDEFF2;
                }
       
                /* Styling table header */
                .v1MsoNormalTable thead td {
                    border-bottom: none;
                }
       
                /* Styling inner table cells */
                .innerTable .firstchildtd {
                    border-left: 3px solid #2D3748; /* Set left border with color */
                    padding-left: 10px; /* Add some padding to align content */
                }
                 .v1MsoNormalTable p.thanks {
                    text-align: left;
                    margin-top: 20px; /* Add some space between the table and the "Thanks, TastyBite" text */
                }
            </style>
        </head>
       
        <body>
            <table class="v1MsoNormalTable" border="0" cellspacing="0" align="center" cellpadding="0">
                <tbody>
                    <tr>
                        <td>
                            <div align="center">
            <h1><img src="path_to_your_logo_image" alt=" Logo"> Invitratech</h1>
        </div>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            <div align="center">
                                <h2>Hi Admin,</h2>
                                <p>We have received a new contact request. Please check the details below.</p>
                                <table class="innerTable"> <!-- Add innerTable class to apply custom styles -->
                                    <tr>
                                        <td class="firstchildtd">Name</td>
                                        <td>'.$name.'</td>
                                    </tr>
                                    <tr>
                                        <td class="firstchildtd">Email</td>
                                        <td>'.$email.'</td>
                                    </tr>
                                    <tr>
                                        <td class="firstchildtd">Contact No.</td>
                                        <td>'.$contact_number.'</td>
                                    </tr>
                                   
                                </table>
                                <p class="thanks">Thanks,<br>Invitratech</p>
                            </div>
                        </td>
                    </tr>
                </tbody>
            </table>
        </body>
       
        </html>
        ';
        // SMTP server configuration
        $smtpServer = "mail.invitratech.com";
        $smtpPort = 25;
        $username = "auth@invitratech.com";
        $password = "Au@2050@ITPL";

        // Create a socket connection to the SMTP server
        $socket = fsockopen($smtpServer, $smtpPort, $errno, $errstr, 30);

        if (!$socket) {
            echo "Failed to connect to SMTP server: $errstr ($errno)";
        } else {
            // Wait for the server to respond
            $response = fread($socket, 4096);

            // Send EHLO command to identify ourselves to the SMTP server
            fputs($socket, "EHLO example.com\r\n");
            $response = fread($socket, 4096);

            // Check if server supports STARTTLS (assuming it's not needed here)

            // Authenticate with the server
            fputs($socket, "AUTH LOGIN\r\n");
            $response = fread($socket, 4096);

            // Send username and password in base64 encoding
            fputs($socket, base64_encode($username) . "\r\n");
            $response = fread($socket, 4096);
            fputs($socket, base64_encode($password) . "\r\n");
            $response = fread($socket, 4096);

            // Send MAIL FROM command
            fputs($socket, "MAIL FROM:<$username>\r\n");
            $response = fread($socket, 4096);

            // Send RCPT TO command
            fputs($socket, "RCPT TO:<$to>\r\n");
            $response = fread($socket, 4096);

            // Send DATA command to start email transmission
            fputs($socket, "DATA\r\n");
            $response = fread($socket, 4096);

            // Send email headers and body
            fputs($socket, "Subject: $subject\r\n");
            fputs($socket, "$headers\r\n");
            fputs($socket, "$message\r\n");
            fputs($socket, ".\r\n");

            // Send QUIT command to close the connection
            fputs($socket, "QUIT\r\n");

            // Close the socket connection
            fclose($socket);

            header("Location: index.php?success=true");
            exit();
        }
    } else {
        include('index.php');
        exit; // Stop further execution

    }

Thursday, 28 December 2023

Nth term formulae

Sure, let's consider the series where we start from 2 and add 2 to each term. For instance, if we want to find the 5th term of this series and also the sum of the series up to the 5th term, we can use the formulas mentioned earlier.


First, the formula for the nth term of an arithmetic series:


\[ a_n = a_1 + (n - 1) \cdot d \]


Given:

- \( a_1 = 2 \) (the first term)

- \( d = 2 \) (the common difference)

- \( n = 5 \) (the term number we want to find)


Let's substitute these values into the formula to find the 5th term:


\[ a_5 = 2 + (5 - 1) \cdot 2 \]

\[ a_5 = 2 + 4 \cdot 2 \]

\[ a_5 = 2 + 8 \]

\[ a_5 = 10 \]


So, the 5th term of the series is 10.


Now, let's find the sum of the series up to the 5th term using the formula for the sum of the first \( n \) terms of an arithmetic series:


\[ S_n = \frac{n}{2} \cdot (a_1 + a_n) \]


Given:

- \( n = 5 \)

- \( a_1 = 2 \)

- \( a_5 = 10 \)


Substituting these values into the formula:


\[ S_5 = \frac{5}{2} \cdot (2 + 10) \]

\[ S_5 = \frac{5}{2} \cdot 12 \]

\[ S_5 = \frac{5 \cdot 12}{2} \]

\[ S_5 = \frac{60}{2} \]

\[ S_5 = 30 \]


Therefore, the sum of the series up to the 5th term is 30. 


The formula used to find the nth term of an arithmetic series is simply called the "nth term formula" or "general term formula" for an arithmetic sequence.


\[ a_n = a_1 + (n - 1) \cdot d \]


Where:

- \( a_n \) is the nth term of the series.

- \( a_1 \) is the first term of the series.

- \( n \) is the position of the term you want to find.

- \( d \) is the common difference between consecutive terms.


Similarly, the formula used to find the sum of the first \( n \) terms of an arithmetic series is known as the "sum of an arithmetic series formula."


\[ S_n = \frac{n}{2} \cdot (a_1 + a_n) \]


Where:

- \( S_n \) is the sum of the first \( n \) terms of the series.

- \( n \) is the number of terms.

- \( a_1 \) is the first term of the series.

- \( a_n \) is the nth term of the series.


These formulas are specific to arithmetic sequences and series and are derived from the properties of arithmetic progressions.

Monday, 30 October 2023

Laravel javascript Fetch method

 $(document).on('click', '.quick-view-btn', function() {

            const rowId = $(this).data('id');

            const url = `{{ url('administrator/Careers/applied-candidate/get-details/') }}/${rowId}`;

 

            getApplicationData(url).then((response) => {

             // Do it your code 

            });

 

            $("#quickViewModal").modal('show');

        });

 

 

        async function getApplicationData(url) {

            try {

                const response = await fetch(url, {

                    method: 'GET',

                    headers: {

                        'Content-type': 'application/json',

                    }

                });

                if (!response.ok) {

                    throw new Error(`Request failed with status: ${response.status}`);

                }

                return response.json();

            } catch (error) {

                throw error;

            }

        }

convert laravel date timestamp to Javascript Date

 const jsDate = new Date(data.applied_at);

                const options = {
                    year: 'numeric',
                    month: 'short',
                    day: 'numeric',
                    hour: '2-digit',
                    minute: '2-digit',
                    hour12: true
                };
                const formattedDate = jsDate.toLocaleString('en-US', options);




Laravel Export data to csv

 use Illuminate\Http\Response; // Define a function to export data to CSV function exportToCSV($exportData, $columns) {     $filename = ...