Thursday, 25 June 2020

PHP Login Registration with Email Verification using OTP



Normally after user registration, we have send email at user register email address for confirm his or her email address. Once User has click on email confirmation link then after that user registration process has been completed with email verification.

But in this post, we have use OTP (One Time Password) method for verify registered user email address. Email verification is a very required process for check registered user has enter right information at the time of registration and it is also useful to prevent spam registration at our web application. For this reason verify user identity, we have to verify his or her email address. In this OTP method, If User has provide us genuine email address then on that email address our system will send one email confirmation email with OTP number. User has to just copy that OTP number and enter in email verification page which will be load after submitting registration form data. In that web page, User has to enter OTP number and submit form. After submitting form user email address will be verified.




In most of the dynamic website, there is user registration form. By fill up user registration form, user can register into web page. So in that registration form, If you have use OTP code for user email address verification, then it is the secure method for verify user email address. In this method, OTP Code will be generated at once user has submitted registration form details, and that OTP code will be received at registered user email address. So, when user has enters the OTP code then PHP web application will verify user email address via that OTP code.

In this tutorial, we will learn User registration process with email verification by using OTP method and here we will send OTP code using email. By using this OTP Code method user email address will be validated once user has enter OTP number which he or she received at their email address. Below you can find the source code of PHP registration system with email verification process using OTP method. In source code you can find how registration form has been made, then after we have first validated user registration form data by using PHP function. After form data verification, we have write PHP script to enter only unique user email data into Mysql database and then after send email with OTP number to registered user email address for email confirmation. After this you can find the source code of email verification by using OTP method.




How to Implement OTP based Login in PHP




In this PHP Registration with email verification using OTP method tutorial, here we have add one more feature like Login using OTP. In this section you can get the solution of Login into system using OTP. We all know OTP means one time password and this OTP number will be generated randomly by using PHP function and that randomly generated OTP number will be stored in Mysql database. So when you have login into system then that OTP number will be expired.

Now we have describe you, how to Login using OTP works. So, when you have login into system, then first you have to enter your login credentials like email address and password details. Then If you have enter right login information then at backend it will generated OTP number and that OTP number will be send to your registered email address. So you have to go to your email address inbox and copy that OTP number and enter into system. Once you have enter valid OTP number then system will validate and you can login into system and that OTP number has been expired. So, in this tutorial, we will OTP based Login system in PHP and below you can find the source code of it.




Source Code


Database



--
-- Database: `testing`
--

-- --------------------------------------------------------

--
-- Table structure for table `login_data`
--

CREATE TABLE `login_data` (
  `login_id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `login_otp` int(6) NOT NULL,
  `last_activity` datetime NOT NULL,
  `login_datetime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

-- --------------------------------------------------------

--
-- Table structure for table `register_user`
--

CREATE TABLE `register_user` (
  `register_user_id` int(11) NOT NULL,
  `user_name` varchar(250) NOT NULL,
  `user_email` varchar(250) NOT NULL,
  `user_password` varchar(250) NOT NULL,
  `user_activation_code` varchar(250) NOT NULL,
  `user_email_status` enum('not verified','verified') NOT NULL,
  `user_otp` int(11) NOT NULL,
  `user_datetime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Indexes for dumped tables
--

--
-- Indexes for table `login_data`
--
ALTER TABLE `login_data`
  ADD PRIMARY KEY (`login_id`);

--
-- Indexes for table `register_user`
--
ALTER TABLE `register_user`
  ADD PRIMARY KEY (`register_user_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `login_data`
--
ALTER TABLE `login_data`
  MODIFY `login_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=5;

--
-- AUTO_INCREMENT for table `register_user`
--
ALTER TABLE `register_user`
  MODIFY `register_user_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=13;





index.php



<?php

//index.php

$connect = new PDO("mysql:host=localhost; dbname=testing", "root", "");

$message = '';
$error_user_name = '';
$error_user_email = '';
$error_user_password = '';
$user_name = '';
$user_email = '';
$user_password = '';

if(isset($_POST["register"]))
{
 if(empty($_POST["user_name"]))
 {
  $error_user_name = "<label class='text-danger'>Enter Name</label>";
 }
 else
 {
  $user_name = trim($_POST["user_name"]);
  $user_name = htmlentities($user_name);
 }

 if(empty($_POST["user_email"]))
 {
  $error_user_email = '<label class="text-danger">Enter Email Address</label>';
 }
 else
 {
  $user_email = trim($_POST["user_email"]);
  if(!filter_var($user_email, FILTER_VALIDATE_EMAIL))
  {
   $error_user_email = '<label class="text-danger">Enter Valid Email Address</label>';
  }
 }

 if(empty($_POST["user_password"]))
 {
  $error_user_password = '<label class="text-danger">Enter Password</label>';
 }
 else
 {
  $user_password = trim($_POST["user_password"]);
  $user_password = password_hash($user_password, PASSWORD_DEFAULT);
 }

 if($error_user_name == '' && $error_user_email == '' && $error_user_password == '')
 {
  $user_activation_code = md5(rand());

  $user_otp = rand(100000, 999999);

  $data = array(
   ':user_name'  => $user_name,
   ':user_email'  => $user_email,
   ':user_password' => $user_password,
   ':user_activation_code' => $user_activation_code,
   ':user_email_status'=> 'not verified',
   ':user_otp'   => $user_otp
  );

  $query = "
  INSERT INTO register_user 
  (user_name, user_email, user_password, user_activation_code, user_email_status, user_otp)
  SELECT * FROM (SELECT :user_name, :user_email, :user_password, :user_activation_code, :user_email_status, :user_otp) AS tmp
  WHERE NOT EXISTS (
      SELECT user_email FROM register_user WHERE user_email = :user_email
  ) LIMIT 1
  ";

  $statement = $connect->prepare($query);

  $statement->execute($data);

  if($connect->lastInsertId() == 0)
  {
   $message = '<label class="text-danger">Email Already Register</label>';
  } 
  else
  {
   require 'class/class.phpmailer.php';
   $mail = new PHPMailer;
   $mail->IsSMTP();
   $mail->Host = 'smtpout.secureserver.net';
   $mail->Port = '80';
   $mail->SMTPAuth = true;
   $mail->Username = 'tutorial@webslesson.info';  //This is not exists, you have to used your own email address.
   $mail->Password = 'password';
   $mail->SMTPSecure = '';
   $mail->From = 'tutorial@webslesson.info';
   $mail->FromName = 'Webslesson';
   $mail->AddAddress($user_email);
   $mail->WordWrap = 50;
   $mail->IsHTML(true);
   $mail->Subject = 'Verification code for Verify Your Email Address';

   $message_body = '
   <p>For verify your email address, enter this verification code when prompted: <b>'.$user_otp.'</b>.</p>
   <p>Sincerely,</p>
   <p>Webslesson.info</p>
   ';
   $mail->Body = $message_body;

   if($mail->Send())
   {
    echo '<script>alert("Please Check Your Email for Verification Code")</script>';

    header('location:email_verify.php?code='.$user_activation_code);
   }
   else
   {
    $message = $mail->ErrorInfo;
   }
  }

 }
}

?>
<!DOCTYPE html>
<html>
 <head>
  <title>PHP Registration with Email Verification using OTP</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="http://code.jquery.com/jquery.js"></script>
     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
 </head>
 <body>
  <br />
  <div class="container">
   <h3 align="center">PHP Registration with Email Verification using OTP</h3>
   <br />
   <div class="panel panel-default">
    <div class="panel-heading">
     <h3 class="panel-title">Registration</h3>
    </div>
    <div class="panel-body">
     <?php echo $message; ?>
     <form method="post">
      <div class="form-group">
       <label>Enter Your Name</label>
       <input type="text" name="user_name" class="form-control" />
       <?php echo $error_user_name; ?>
      </div>
      <div class="form-group">
       <label>Enter Your Email</label>
       <input type="text" name="user_email" class="form-control" />
       <?php echo $error_user_email; ?>
      </div>
      <div class="form-group">
       <label>Enter Your Password</label>
       <input type="password" name="user_password" class="form-control" />
       <?php echo $error_user_password; ?>
      </div>
      <div class="form-group">
       <input type="submit" name="register" class="btn btn-success" value="Click to Register" />
      </div>
     </form>
    </div>
   </div>
  </div>
  <br />
  <br />
 </body>
</html>


email_verify.php



<?php

//email_verify.php

$connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");

$error_user_otp = '';
$user_activation_code = '';
$message = '';

if(isset($_GET["code"]))
{
 $user_activation_code = $_GET["code"];

 if(isset($_POST["submit"]))
 {
  if(empty($_POST["user_otp"]))
  {
   $error_user_otp = 'Enter OTP Number';
  }
  else
  {
   $query = "
   SELECT * FROM register_user 
   WHERE user_activation_code = '".$user_activation_code."' 
   AND user_otp = '".trim($_POST["user_otp"])."'
   ";

   $statement = $connect->prepare($query);

   $statement->execute();

   $total_row = $statement->rowCount();

   if($total_row > 0)
   {
    $query = "
    UPDATE register_user 
    SET user_email_status = 'verified' 
    WHERE user_activation_code = '".$user_activation_code."'
    ";

    $statement = $connect->prepare($query);

    if($statement->execute())
    {
     header('location:login.php?register=success');
    }
   }
   else
   {
    $message = '<label class="text-danger">Invalid OTP Number</label>';
   }
  }
 }
}
else
{
 $message = '<label class="text-danger">Invalid Url</label>';
}

?>
<!DOCTYPE html>
<html>
 <head>
  <title>PHP Registration with Email Verification using OTP</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="http://code.jquery.com/jquery.js"></script>
     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
 </head>
 <body>
  <br />
  <div class="container">
   <h3 align="center">PHP Registration with Email Verification using OTP</h3>
   <br />
   <div class="panel panel-default">
    <div class="panel-heading">
     <h3 class="panel-title">Enter OTP Number</h3>
    </div>
    <div class="panel-body">
     <?php echo $message; ?>
     <form method="POST">
      <div class="form-group">
       <label>Enter OTP Number</label>
       <input type="text" name="user_otp" class="form-control" />
       <?php echo $error_user_otp; ?>
      </div>
      <div class="form-group">
       <input type="submit" name="submit" class="btn btn-success" value="Submit" />
      </div>
     </form>
    </div>
   </div>
  </div>
  <br />
  <br />
 </body>
</html>



login.php



<?php

session_start();

if(isset($_SESSION["user_id"]))
{
 header("location:home.php");
}

?>

<!DOCTYPE html>
<html>
 <head>
  <title>PHP Login with OTP Authentication</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="http://code.jquery.com/jquery.js"></script>
     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
 </head>
 <body>
  <br />
  <div class="container">
   <h3 align="center">PHP Login with OTP Authentication</h3>
   <br />

   <?php
   if(isset($_GET["register"]))
   {
    if($_GET["register"] == 'success')
    {
     echo '
     <h1 class="text-success">Email Successfully verified, Registration Process Completed...</h1>
     ';
    }
   }
   ?>

   <div class="row">
    <div class="col-md-3">&nbsp;</div>
    <div class="col-md-6">
     <div class="panel panel-default">
      <div class="panel-heading">
       <h3 class="panel-title">Login</h3>
      </div>
      <div class="panel-body">
       <form method="POST" id="login_form">
        <div class="form-group" id="email_area">
         <label>Enter Email Address</label>
         <input type="text" name="user_email" id="user_email" class="form-control" />
         <span id="user_email_error" class="text-danger"></span>
        </div>
        <div class="form-group" id="password_area" style="display:none;">
         <label>Enter password</label>
         <input type="password" name="user_password" id="user_password" class="form-control" />
         <span id="user_password_error" class="text-danger"></span>
        </div>
        <div class="form-group" id="otp_area" style="display:none;">
         <label>Enter OTP Number</label>
         <input type="text" name="user_otp" id="user_otp" class="form-control" />
         <span id="user_otp_error" class="text-danger"></span>
        </div>
        <div class="form-group" align="right">
         <input type="hidden" name="action" id="action" value="email" />
         <input type="submit" name="next" id="next" class="btn btn-primary" value="Next" />
        </div>
       </form>
      </div>
     </div>
    </div>
   </div>
   
  </div>
  <br />
  <br />
 </body>
</html>

<script>

$(document).ready(function(){
 $('#login_form').on('submit', function(event){
  event.preventDefault();
  var action = $('#action').val();
  $.ajax({
   url:"login_verify.php",
   method:"POST",
   data:$(this).serialize(),
   dataType:"json",
   beforeSend:function()
   {
    $('#next').attr('disabled', 'disabled');
   },
   success:function(data)
   {
    $('#next').attr('disabled', false);
    if(action == 'email')
    {
     if(data.error != '')
     {
      $('#user_email_error').text(data.error);
     }
     else
     {
      $('#user_email_error').text('');
      $('#email_area').css('display', 'none');
      $('#password_area').css('display', 'block');
     }
    }
    else if(action == 'password')
    {
     if(data.error != '')
     {
      $('#user_password_error').text(data.error);
     }
     else
     {
      $('#user_password_error').text('');
      $('#password_area').css('display', 'none');
      $('#otp_area').css('display', 'block');
     }
    }
    else
    {
     if(data.error != '')
     {
      $('#user_otp_error').text(data.error);
     }
     else
     {
      window.location.replace("home.php");
     }
    }

    $('#action').val(data.next_action);
   }
  })
 });
});

</script>


login_verify.php



<?php

//login_verify.php

$connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");

session_start();

$error = '';

$next_action = '';

sleep(2);

if(isset($_POST["action"]))
{
 if($_POST["action"] == 'email')
 {
  if($_POST["user_email"] != '')
  {
   $data = array(
    ':user_email' => $_POST["user_email"]
   );

   $query = "
   SELECT * FROM register_user 
   WHERE user_email = :user_email
   ";

   $statement = $connect->prepare($query);

   $statement->execute($data);

   $total_row = $statement->rowCount();

   if($total_row == 0)
   {
    $error = 'Email Address not found';

    $next_action = 'email';
   }
   else
   {
    $result = $statement->fetchAll();

    foreach($result as $row)
    {
     $_SESSION["register_user_id"] = $row["register_user_id"];

     $_SESSION["user_name"] = $row["user_name"];

     $_SESSION['user_email'] = $row["user_email"];

     $_SESSION["user_password"] = $row["user_password"];
    }
    $next_action = 'password';
   }
  }
  else
  {
   $error = 'Email Address is Required';

   $next_action = 'email';
  }
 }

 if($_POST["action"] == 'password')
 {
  if($_POST["user_password"] != '')
  {
   if(password_verify($_POST["user_password"], $_SESSION["user_password"]))
   {
    $login_otp = rand(100000,999999);

    $data = array(
     ':user_id'  => $_SESSION["register_user_id"],
     ':login_otp' => $login_otp,
     ':last_activity'=> date('d-m-y h:i:s')
    );

    $query = "
    INSERT INTO login_data 
    (user_id, login_otp, last_activity) 
    VALUES (:user_id, :login_otp, :last_activity)
    ";

    $statement = $connect->prepare($query);

    if($statement->execute($data))
    {
     $_SESSION['login_id'] = $connect->lastInsertId();
     $_SESSION['login_otp'] = $login_otp;

     require 'class/class.phpmailer.php';

     $mail = new PHPMailer;

     $mail->IsSMTP();

     $mail->Host = 'smtpout.secureserver.net';

     $mail->Port = '80';

     $mail->SMTPAuth = true;

     $mail->Username = 'xxxxxxxxxxxxxx';
     $mail->Password = 'xxxxxxxxxxxxxx';

     $mail->SMTPSecure = '';

     $mail->From = 'tutorial@webslesson.info';

     $mail->FromName = 'Webslesson';

     $mail->AddAddress($_SESSION["user_email"]);

     $mail->WordWrap = 50;

     $mail->IsHTML(true);

     $mail->Subject = 'Verification code for Login';

     $message_body = '
     <p>For verify your login details, enter this verification code when prompted: <b>'.$login_otp.'</b>.</p>
     <p>Sincerely,</p>
     <p>Webslesson.info</p>
     ';

     $mail->Body = $message_body;

     if($mail->Send())
     {
      $next_action = 'otp';
     }
     else
     {
      $error = '<label class="text-danger">'.$mail->ErrorInfo.'</label>';
      $next_action = 'password';
     }
    }
   }
   else
   {
    $error = 'Wrong Password';
    $next_action = 'password';
   }
  }
  else
  {
   $error = 'Password is Required';
   $next_action = 'password';
  }
 }

 if($_POST["action"] == "otp")
 {
  if($_POST["user_otp"] != '')
  {
   if($_SESSION['login_otp'] == $_POST["user_otp"])
   {
    $_SESSION['user_id'] = $_SESSION['register_user_id'];
    unset($_SESSION["register_user_id"]);
    unset($_SESSION["user_email"]);
    unset($_SESSION["user_password"]);
    unset($_SESSION["login_otp"]);
   }
   else
   {
    $error = 'Wrong OTP Number';
    $next_action = 'otp';
   }
  }
  else
  {
   $error = 'OTP Number is required';
   $next_action = 'otp';
  }
 }





 $output = array(
  'error'   => $error,
  'next_action' => $next_action
 );

 echo json_encode($output);
}


?>


home.php



<?php

//home.php

session_start();

if(!isset($_SESSION["user_id"]))
{
 header("location:login.php");
}

?>
<!DOCTYPE html>
<html>
 <head>
  <title>PHP Login with OTP Authentication</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="http://code.jquery.com/jquery.js"></script>
     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
 </head>
 <body>
  <br />
  <div class="container">
   <h3 align="center">PHP Login with OTP Authentication</h3>
   <br />
   <br />
   <h1 align="center">Welcome <?php echo $_SESSION["user_name"]; ?></h1>
   <p align="center"><a href="logout.php">Logout</a></p>
  </div>
  <br />
  <br />
 </body>
</html>


logout.php



<?php

//logout.php

session_start();

session_destroy();

header("location:login.php");

?>





Friday, 19 June 2020

Import Selected CSV File Column in PHP using Ajax jQuery



On the web, we have seen lots of articles or tutorial on How to import CSV file data into Mysql Database by using PHP script. But there are none of the tutorials has define how can we define particular CSV file column data at the time of importing file, and that selected column data has been imported into Mysql table by using PHP script with Ajax jQuery. For solve the problem of CSV file Column Mapping here we have make this tutorial in which we have step by step describe the process of CSV file column mapping in PHP using Ajax jQuery.

This tutorial has divided in following different part.
  • Make Upload Form for Select CSV File
  • Convert CSV File into HTML Table
  • Write jQuery Code for Column Selection
  • Import Select Column Data



Before we have going to step, first we must have to see our database structure. So below you can find this tutorial Mysql table definition.


--
-- Database: `testing`
--

-- --------------------------------------------------------

--
-- Table structure for table `csv_file`
--

CREATE TABLE `csv_file` (
  `id` int(11) NOT NULL,
  `first_name` varchar(255) NOT NULL,
  `last_name` varchar(255) NOT NULL,
  `email` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Indexes for table `csv_file`
--
ALTER TABLE `csv_file`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `csv_file`
--
ALTER TABLE `csv_file`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;
COMMIT;


Here in this Mysql table there is only three column in which we want to import CSV file data. Now below we have to CSV file structure.


Company Name,First Name,Last Name,Address,City,State,ZIP/PIN CODE,Country,Phone Number,Email
Prestiga-Biz,Barbara,Motes,3029 Harrison Street,Oakland,CA,94612,USA,415-481-0998,barbarapmotes@armyspy.com
McDade's,Paul,Minter,1376 Orphan Road,Long Lake,WI,54542,USA,715-967-2332,paulcminter@rhyta.com
Penn Fruit,Robin,Morton,4609 Eastland Avenue,Jackson,MS,39211,USA,601-348-3248,robinamorton@armyspy.com
Frank's Nursery & Crafts,Alvin,Sarvis,83 Star Trek Drive,Pensacola,FL,32501,USA,850-356-1961,AlvinMSarvis@armyspy.com
Media Play,Daniel,Retana,1114 Bel Meadow Drive,Arrowhead,CA ,92352,USA,909-336-8296,DanielSRetana@teleworm.us
Cut Rite,Eva,Tallent,4138 Shadowmar Drive,Metairie,LA,70006,USA,504-779-1200,EvaTTallent@dayrep.com
Matrix Design,Charles,Astorga,410 Westwood Avenue,Garden City,NY ,11530,USA,516-805-0092,CharlesAAstorga@armyspy.com
Century House,Jane,Lim,2305 Reppert Coal Road,Southfield,MI,48075,USA,586-970-6260,JanePLim@armyspy.com
Life's Gold,Tom,Garcia,518 Seth Street,Gustine,TX,76455,USA,325-667-9370,TomKGarcia@armyspy.com
Two Pesos,Aaron,Lovejoy,2448 Settlers Lane,New York,NY,10007,USA,917-826-2371,AaronRLovejoy@armyspy.com
Smitty's Marketplace,Susan,Reyes,4402 Stuart Street,Sewickley,PA,15143,USA,724-417-4584,SusanDReyes@armyspy.com
Waves Music,Susan,Jackson,1196 Archwood Avenue,Cheyenne,WY,82003,USA,307-871-1265,SusanRJackson@rhyta.com
Realty Depot,Mary,Shepard,2632 Scott Street,Poughkeepsie,NY,12601,USA,845-471-7357,MaryEShepard@armyspy.com
Martin's,Sadie,Hill,148 Peaceful Lane,Warrensville Heights,OH,44128,USA,216-390-5580,SadieAHill@dayrep.com
Wickes Furniture,Stephen,Flynn,4378 Jenna Lane,Ames,IA,50010,USA,515-233-9027,StephenJFlynn@teleworm.us
Larry's Markets,Beth,Holloway,3915 Essex Court,South Burlington,VT,5403,USA,802-272-7414,BethHHolloway@rhyta.com
Handy Dan,Mildred,Hoyt,2626 Johnstown Road,Cary,IL,60013,USA,847-462-6919,MildredAHoyt@armyspy.com
Laura Ashley Mother & Child,Karen,Walker,3659 Shingleton Road,Portage,MI,49002,USA,269-327-9698,KarenBWalker@rhyta.com
Harmony House,Lucille,Wilson,644 Villa Drive,South Bend,IN,46601,USA,574-303-6598,LucilleZWilson@jourrapide.com
Suadela Investment,Jimmie,Cornwell,2533 Melody Lane,Lively,VA,22503,USA,804-462-5048,JimmieMCornwell@jourrapide.com
American Appliance,Marion,Davis,2905 Denver Avenue,City Of Commerce,CA,90040,USA,951-314-7204,MarionVDavis@armyspy.com
The Warner Brothers Store,Sonia,Johnson,1510 Bel Meadow Drive,Los Angeles,CA,90017,USA,909-269-6784,SoniaCJohnson@jourrapide.com
Gart Sports,Brandy,Voyles,2538 Broadcast Drive,Washington,VA,20011,USA,703-956-0582,BrandyRVoyles@rhyta.com
Irving's Sporting Goods,Deborah,Gossard,2655 Ashton Lane,Austin,TX,78756,USA,512-465-9149,DeborahGGossard@rhyta.com
Yardbirds Home Center,Dawn,Guerrero,753 Saints Alley,Tampa,FL,33614,USA,813-787-0466,DawnAGuerrero@teleworm.us
Multicerv,Priscilla,Holloway,4957 Custer Street,Smethport,PA,16749,USA,814-887-3339,PriscillaRHolloway@armyspy.com
Colonial Stores,Jay,Crowder,4281 Ryder Avenue,Bellevue,WA,98004,USA,425-384-6261,JayECrowder@dayrep.com
Balanced Fortune,Ashley,Hemphill,2042 Olen Thomas Drive,Rosston,TX,76263,USA,940-768-7053,AshleyJHemphill@jourrapide.com
Lee Wards,Debra,Harrington,532 Seltice Way,Kellogg,ID,83837,USA,208-783-0049,DebraFHarrington@armyspy.com
Garden Guru,Anna,Brooks,1332 Brown Street,San Francisco,CA,94124,USA,925-999-9078,AnnaEBrooks@rhyta.com



So, Above we can see that there is 10 column in CSV file. Now we have to make feature like when we have upload CSV file file then we can define three column and only three column data must be import into above Mysql table. So below you can find the solution of CSV file column mapping in PHP script using Ajax jQuery.



1 - Make Upload Form for Select CSV File


For make CSV file column mapping script. So first we have to make One upload form for select CSV file from our local computer. After creating HTML form for upload csv file. Then after we have to write jquery code and in that code we have make Ajax call which will send CSV file to server script. Below you can find the source code of this steps.

index.php



<!DOCTYPE html>
<html>
   <head>
     <title>CSV Column Mapping in PHP</title>
     <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <script src="http://code.jquery.com/jquery.js"></script>
     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
      <style>
      .table tbody tr th
      {
        min-width: 200px;
      }

      .table tbody tr td
      {
        min-width: 200px;
      }

      </style>
   </head>
   <body>
    <div class="container">
     <br />
     <br />
      <h1 align="center">CSV Column Mapping in PHP</h1>
      <br />
        <div id="message"></div>
      <div class="panel panel-default">
          <div class="panel-heading">
            <h3 class="panel-title">Select CSV File</h3>
          </div>
          <div class="panel-body">
            <div class="row" id="upload_area">
              <form method="post" id="upload_form" enctype="multipart/form-data">
                <div class="col-md-6" align="right">Select File</div>
                <div class="col-md-6">
                  <input type="file" name="file" id="csv_file" />
                </div>
                <br /><br /><br />
                <div class="col-md-12" align="center">
                  <input type="submit" name="upload_file" id="upload_file" class="btn btn-primary" value="Upload" />
                </div>
              </form>
              
            </div>
            <div class="table-responsive" id="process_area">

            </div>
          </div>
        </div>
     </div>
     
   </body>
</html>

<script>
$(document).ready(function(){

  $('#upload_form').on('submit', function(event){

    event.preventDefault();
    $.ajax({
      url:"upload.php",
      method:"POST",
      data:new FormData(this),
      dataType:'json',
      contentType:false,
      cache:false,
      processData:false,
      success:function(data)
      {
        if(data.error != '')
        {
          $('#message').html('<div class="alert alert-danger">'+data.error+'</div>');
        }
        else
        {
          $('#process_area').html(data.output);
          $('#upload_area').css('display', 'none');
        }
      }
    });

  });

});
</script>






2 - Convert CSV File into HTML Table


In second steps, First we have to check user has select file or not. If User has select file then we have to check selected file is .csv file or not if selected file is CSV file then we have to fetch data from CSV file. From this first line of csv file, we have to count total number of column of CSV file and based on that column we have to make select box for column selection for all column in html table format. After this all csv file data has been store in SESSION variable for future use of import data and top five row of CSV file has been convert into HTML table. After this we have to make import button and append that button code in HTML table code and send whole data to Ajax request in json string format.




upload.php



<?php

//upload.php

session_start();

$error = '';

$html = '';

if($_FILES['file']['name'] != '')
{
 $file_array = explode(".", $_FILES['file']['name']);

 $extension = end($file_array);

 if($extension == 'csv')
 {
  $file_data = fopen($_FILES['file']['tmp_name'], 'r');

  $file_header = fgetcsv($file_data);

  $html .= '<table class="table table-bordered"><tr>';

  for($count = 0; $count < count($file_header); $count++)
  {
   $html .= '
   <th>
    <select name="set_column_data" class="form-control set_column_data" data-column_number="'.$count.'">
     <option value="">Set Count Data</option>
     <option value="first_name">First Name</option>
     <option value="last_name">Last Name</option>
     <option value="email">Email</option>
    </select>
   </th>
   ';
  }

  $html .= '</tr>';

  $limit = 0;

  while(($row = fgetcsv($file_data)) !== FALSE)
  {
   $limit++;

   if($limit < 6)
   {
    $html .= '<tr>';

    for($count = 0; $count < count($row); $count++)
    {
     $html .= '<td>'.$row[$count].'</td>';
    }

    $html .= '</tr>';
   }

   $temp_data[] = $row;
  }

  $_SESSION['file_data'] = $temp_data;

  $html .= '
  </table>
  <br />
  <div align="right">
   <button type="button" name="import" id="import" class="btn btn-success" disabled>Import</button>
  </div>
  <br />
  ';
 }
 else
 {
  $error = 'Only <b>.csv</b> file allowed';
 }
}
else
{
 $error = 'Please Select CSV File';
}

$output = array(
 'error'  => $error,
 'output' => $html
);

echo json_encode($output);


?>



3 - Write jQuery Code for Column Selection


Once selected CSV file data has been uploaded and after this convert that file data into html table format and display on web page. Now in third step we have to write jquery code for validate column selection or mapping. So, we have to write jquery script, firts it will check user must have to select at least three column this is because in database there is three column in which we want to import data. If user select less than or greater than three column then import button will be disabled, but if user select three different column then import button will enable. jQuery will also check user must define define unique column as per Mysql table, if user select two column from html table with same Mysql table then also import button will disable. All unique column select box option we have to store in variable, and this variable value we will be used for define column number at the time of importing of data. So this validation will check in this part of jQuery script.



index.php



<!DOCTYPE html>
<html>
   <head>
     <title>CSV Column Mapping in PHP</title>
     <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <script src="http://code.jquery.com/jquery.js"></script>
     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
      <style>
      .table tbody tr th
      {
        min-width: 200px;
      }

      .table tbody tr td
      {
        min-width: 200px;
      }

      </style>
   </head>
   <body>
    <div class="container">
     <br />
     <br />
      <h1 align="center">CSV Column Mapping in PHP</h1>
      <br />
        <div id="message"></div>
      <div class="panel panel-default">
          <div class="panel-heading">
            <h3 class="panel-title">Select CSV File</h3>
          </div>
          <div class="panel-body">
            <div class="row" id="upload_area">
              <form method="post" id="upload_form" enctype="multipart/form-data">
                <div class="col-md-6" align="right">Select File</div>
                <div class="col-md-6">
                  <input type="file" name="file" id="csv_file" />
                </div>
                <br /><br /><br />
                <div class="col-md-12" align="center">
                  <input type="submit" name="upload_file" id="upload_file" class="btn btn-primary" value="Upload" />
                </div>
              </form>
              
            </div>
            <div class="table-responsive" id="process_area">

            </div>
          </div>
        </div>
     </div>
     
   </body>
</html>

<script>
$(document).ready(function(){

  $('#upload_form').on('submit', function(event){

    event.preventDefault();
    $.ajax({
      url:"upload.php",
      method:"POST",
      data:new FormData(this),
      dataType:'json',
      contentType:false,
      cache:false,
      processData:false,
      success:function(data)
      {
        if(data.error != '')
        {
          $('#message').html('<div class="alert alert-danger">'+data.error+'</div>');
        }
        else
        {
          $('#process_area').html(data.output);
          $('#upload_area').css('display', 'none');
        }
      }
    });

  });

  var total_selection = 0;

  var first_name = 0;

  var last_name = 0;

  var email = 0;

  var column_data = [];

  $(document).on('change', '.set_column_data', function(){

    var column_name = $(this).val();

    var column_number = $(this).data('column_number');

    if(column_name in column_data)
    {
      alert('You have already define '+column_name+ ' column');

      $(this).val('');

      return false;
    }

    if(column_name != '')
    {
      column_data[column_name] = column_number;
    }
    else
    {
      const entries = Object.entries(column_data);

      for(const [key, value] of entries)
      {
        if(value == column_number)
        {
          delete column_data[key];
        }
      }
    }

    total_selection = Object.keys(column_data).length;

    if(total_selection == 3)
    {
      $('#import').attr('disabled', false);

      first_name = column_data.first_name;

      last_name = column_data.last_name;

      email = column_data.email;
    }
    else
    {
      $('#import').attr('disabled', 'disabled');
    }

  });
  
});
</script>



4 - Import Select Column Data


This is last part of CSV file column mapping tutorial and in this part we have to import selected CSV file column data into Mysql table. In third part, we have write jQuery script and define three column with unique option. Now in this part, we have to write jQuery script in which we have to make Ajax call which will send local variable in which we have store column number which has been get in third part. Based on this variable column number at PHP script will import only that column data into Mysql table. At PHP script CSV file data will be get from SESSION variable in which we have store CSV file data in second steps.




index.php



<!DOCTYPE html>
<html>
   <head>
     <title>CSV Column Mapping in PHP</title>
     <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <script src="http://code.jquery.com/jquery.js"></script>
     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
      <style>
      .table tbody tr th
      {
        min-width: 200px;
      }

      .table tbody tr td
      {
        min-width: 200px;
      }

      </style>
   </head>
   <body>
    <div class="container">
     <br />
     <br />
      <h1 align="center">CSV Column Mapping in PHP</h1>
      <br />
        <div id="message"></div>
      <div class="panel panel-default">
          <div class="panel-heading">
            <h3 class="panel-title">Select CSV File</h3>
          </div>
          <div class="panel-body">
            <div class="row" id="upload_area">
              <form method="post" id="upload_form" enctype="multipart/form-data">
                <div class="col-md-6" align="right">Select File</div>
                <div class="col-md-6">
                  <input type="file" name="file" id="csv_file" />
                </div>
                <br /><br /><br />
                <div class="col-md-12" align="center">
                  <input type="submit" name="upload_file" id="upload_file" class="btn btn-primary" value="Upload" />
                </div>
              </form>
              
            </div>
            <div class="table-responsive" id="process_area">

            </div>
          </div>
        </div>
     </div>
     
   </body>
</html>

<script>
$(document).ready(function(){

  $('#upload_form').on('submit', function(event){

    event.preventDefault();
    $.ajax({
      url:"upload.php",
      method:"POST",
      data:new FormData(this),
      dataType:'json',
      contentType:false,
      cache:false,
      processData:false,
      success:function(data)
      {
        if(data.error != '')
        {
          $('#message').html('<div class="alert alert-danger">'+data.error+'</div>');
        }
        else
        {
          $('#process_area').html(data.output);
          $('#upload_area').css('display', 'none');
        }
      }
    });

  });

  var total_selection = 0;

  var first_name = 0;

  var last_name = 0;

  var email = 0;

  var column_data = [];

  $(document).on('change', '.set_column_data', function(){

    var column_name = $(this).val();

    var column_number = $(this).data('column_number');

    if(column_name in column_data)
    {
      alert('You have already define '+column_name+ ' column');

      $(this).val('');

      return false;
    }

    if(column_name != '')
    {
      column_data[column_name] = column_number;
    }
    else
    {
      const entries = Object.entries(column_data);

      for(const [key, value] of entries)
      {
        if(value == column_number)
        {
          delete column_data[key];
        }
      }
    }

    total_selection = Object.keys(column_data).length;

    if(total_selection == 3)
    {
      $('#import').attr('disabled', false);

      first_name = column_data.first_name;

      last_name = column_data.last_name;

      email = column_data.email;
    }
    else
    {
      $('#import').attr('disabled', 'disabled');
    }

  });

  $(document).on('click', '#import', function(event){

    event.preventDefault();

    $.ajax({
      url:"import.php",
      method:"POST",
      data:{first_name:first_name, last_name:last_name, email:email},
      beforeSend:function(){
        $('#import').attr('disabled', 'disabled');
        $('#import').text('Importing...');
      },
      success:function(data)
      {
        $('#import').attr('disabled', false);
        $('#import').text('Import');
        $('#process_area').css('display', 'none');
        $('#upload_area').css('display', 'block');
        $('#upload_form')[0].reset();
        $('#message').html("<div class='alert alert-success'>"+data+"</div>");
      }
    })

  });
  
});
</script>


import.php



<?php

//import.php

if(isset($_POST["first_name"]))
{
 $connect = new PDO("mysql:host=localhost; dbname=testing", "root", "");

 session_start();

 $file_data = $_SESSION['file_data'];

 unset($_SESSION['file_data']);

 foreach($file_data as $row)
 {
  $data[] = '("'.$row[$_POST["first_name"]].'", "'.$row[$_POST["last_name"]].'", "'.$row[$_POST["email"]].'")';
 }

 if(isset($data))
 {
  $query = "
  INSERT INTO csv_file 
  (first_name, last_name, email) 
  VALUES ".implode(",", $data)."
  ";

  $statement = $connect->prepare($query);

  if($statement->execute())
  {
   echo 'Data Imported Successfully';
  }
 }
}



?>


So, In this tutorial, we have step by step sees how can we map CSV file column or define CSV file column and then after we have import or insert that define or selected column data into Mysql table by using PHP with Ajax jQuery. IF you have find any simple way for map csv file column in PHP then you are welcome and Let us know in the comments section.

Wednesday, 3 June 2020

Vue.js Autocomplete Textbox using PHP Mysql



In this PHP and Vue.js tutorials, We are going to learn how to use Ajax live search for build Autocomplete feature using Vue JS in PHP application with Mysql database. Here We will learn How to make an autocomplete component using Vue.js with PHP script and Mysql Database.

In this tutorial, we will build simple application for demonstrate the example of Autocomplete in Vue.js using PHP and Mysql. We will use Axios package for send Ajax request to fetch data from Mysql table.

As a web developer, we have already familiar with functionality of Ajax Live Dynamic Search or Autocomplete feature for search activity. In current scenario we all have made search on Google search engine or Youtube and any other social media website on internet, then we have seen like search with autocomplete. This type of live search or Autocomplete feature has been made by using Ajax technology, which will provide you search result or search query suggestion, which will be related with search query which you have entered in search textbox.

For make Ajax live search or Autocomplete feature for your website, there are many tools like jQuery UI or Typeahead etc. are available for create Autocomplete feature for your website. But here we will use Vue.js will be used with PHP script and Mysql database for build Autocomplete textbox. Here we have use Vue.js library for build Autocomplete feature, this is because Vue.js has component instance, by using Vue.js component, we can make HTML template which we can reuse in Vue.js application again and again.

So, in this article we will create ajax search autocomplete using Vue.js PHP Mysql and for this we will Axios package for use the functionality of ajax. Ajax is required for create Autocomplete feature, this is because it will fetch data from Mysql database without refresh of web page. So, in this post, we will make ajax autocomplete search with Vue.js using PHP with Mysql database. Below you can find complete source of Vue.js autocomplete from Mysql database using PHP.


Vue.js Autocomplete Textbox using PHP Mysql




Source Code

Mysql Database



--
-- Database: `testing`
--

-- --------------------------------------------------------

--
-- Table structure for table `apps_countries`
--

CREATE TABLE `apps_countries` (
  `id` int(11) NOT NULL,
  `country_code` varchar(2) NOT NULL DEFAULT '',
  `country_name` varchar(100) NOT NULL DEFAULT ''
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

--
-- Dumping data for table `apps_countries`
--

INSERT INTO `apps_countries` (`id`, `country_code`, `country_name`) VALUES
(1, 'AF', 'Afghanistan'),
(2, 'AL', 'Albania'),
(3, 'DZ', 'Algeria'),
(4, 'DS', 'American Samoa'),
(5, 'AD', 'Andorra'),
(6, 'AO', 'Angola'),
(7, 'AI', 'Anguilla'),
(8, 'AQ', 'Antarctica'),
(9, 'AG', 'Antigua and Barbuda'),
(10, 'AR', 'Argentina'),
(11, 'AM', 'Armenia'),
(12, 'AW', 'Aruba'),
(13, 'AU', 'Australia'),
(14, 'AT', 'Austria'),
(15, 'AZ', 'Azerbaijan'),
(16, 'BS', 'Bahamas'),
(17, 'BH', 'Bahrain'),
(18, 'BD', 'Bangladesh'),
(19, 'BB', 'Barbados'),
(20, 'BY', 'Belarus'),
(21, 'BE', 'Belgium'),
(22, 'BZ', 'Belize'),
(23, 'BJ', 'Benin'),
(24, 'BM', 'Bermuda'),
(25, 'BT', 'Bhutan'),
(26, 'BO', 'Bolivia'),
(27, 'BA', 'Bosnia and Herzegovina'),
(28, 'BW', 'Botswana'),
(29, 'BV', 'Bouvet Island'),
(30, 'BR', 'Brazil'),
(31, 'IO', 'British Indian Ocean Territory'),
(32, 'BN', 'Brunei Darussalam'),
(33, 'BG', 'Bulgaria'),
(34, 'BF', 'Burkina Faso'),
(35, 'BI', 'Burundi'),
(36, 'KH', 'Cambodia'),
(37, 'CM', 'Cameroon'),
(38, 'CA', 'Canada'),
(39, 'CV', 'Cape Verde'),
(40, 'KY', 'Cayman Islands'),
(41, 'CF', 'Central African Republic'),
(42, 'TD', 'Chad'),
(43, 'CL', 'Chile'),
(44, 'CN', 'China'),
(45, 'CX', 'Christmas Island'),
(46, 'CC', 'Cocos (Keeling) Islands'),
(47, 'CO', 'Colombia'),
(48, 'KM', 'Comoros'),
(49, 'CG', 'Congo'),
(50, 'CK', 'Cook Islands'),
(51, 'CR', 'Costa Rica'),
(52, 'HR', 'Croatia (Hrvatska)'),
(53, 'CU', 'Cuba'),
(54, 'CY', 'Cyprus'),
(55, 'CZ', 'Czech Republic'),
(56, 'DK', 'Denmark'),
(57, 'DJ', 'Djibouti'),
(58, 'DM', 'Dominica'),
(59, 'DO', 'Dominican Republic'),
(60, 'TP', 'East Timor'),
(61, 'EC', 'Ecuador'),
(62, 'EG', 'Egypt'),
(63, 'SV', 'El Salvador'),
(64, 'GQ', 'Equatorial Guinea'),
(65, 'ER', 'Eritrea'),
(66, 'EE', 'Estonia'),
(67, 'ET', 'Ethiopia'),
(68, 'FK', 'Falkland Islands (Malvinas)'),
(69, 'FO', 'Faroe Islands'),
(70, 'FJ', 'Fiji'),
(71, 'FI', 'Finland'),
(72, 'FR', 'France'),
(73, 'FX', 'France, Metropolitan'),
(74, 'GF', 'French Guiana'),
(75, 'PF', 'French Polynesia'),
(76, 'TF', 'French Southern Territories'),
(77, 'GA', 'Gabon'),
(78, 'GM', 'Gambia'),
(79, 'GE', 'Georgia'),
(80, 'DE', 'Germany'),
(81, 'GH', 'Ghana'),
(82, 'GI', 'Gibraltar'),
(83, 'GK', 'Guernsey'),
(84, 'GR', 'Greece'),
(85, 'GL', 'Greenland'),
(86, 'GD', 'Grenada'),
(87, 'GP', 'Guadeloupe'),
(88, 'GU', 'Guam'),
(89, 'GT', 'Guatemala'),
(90, 'GN', 'Guinea'),
(91, 'GW', 'Guinea-Bissau'),
(92, 'GY', 'Guyana'),
(93, 'HT', 'Haiti'),
(94, 'HM', 'Heard and Mc Donald Islands'),
(95, 'HN', 'Honduras'),
(96, 'HK', 'Hong Kong'),
(97, 'HU', 'Hungary'),
(98, 'IS', 'Iceland'),
(99, 'IN', 'India'),
(100, 'IM', 'Isle of Man'),
(101, 'ID', 'Indonesia'),
(102, 'IR', 'Iran (Islamic Republic of)'),
(103, 'IQ', 'Iraq'),
(104, 'IE', 'Ireland'),
(105, 'IL', 'Israel'),
(106, 'IT', 'Italy'),
(107, 'CI', 'Ivory Coast'),
(108, 'JE', 'Jersey'),
(109, 'JM', 'Jamaica'),
(110, 'JP', 'Japan'),
(111, 'JO', 'Jordan'),
(112, 'KZ', 'Kazakhstan'),
(113, 'KE', 'Kenya'),
(114, 'KI', 'Kiribati'),
(115, 'KP', 'Korea, Democratic People\'s Republic of'),
(116, 'KR', 'Korea, Republic of'),
(117, 'XK', 'Kosovo'),
(118, 'KW', 'Kuwait'),
(119, 'KG', 'Kyrgyzstan'),
(120, 'LA', 'Lao People\'s Democratic Republic'),
(121, 'LV', 'Latvia'),
(122, 'LB', 'Lebanon'),
(123, 'LS', 'Lesotho'),
(124, 'LR', 'Liberia'),
(125, 'LY', 'Libyan Arab Jamahiriya'),
(126, 'LI', 'Liechtenstein'),
(127, 'LT', 'Lithuania'),
(128, 'LU', 'Luxembourg'),
(129, 'MO', 'Macau'),
(130, 'MK', 'Macedonia'),
(131, 'MG', 'Madagascar'),
(132, 'MW', 'Malawi'),
(133, 'MY', 'Malaysia'),
(134, 'MV', 'Maldives'),
(135, 'ML', 'Mali'),
(136, 'MT', 'Malta'),
(137, 'MH', 'Marshall Islands'),
(138, 'MQ', 'Martinique'),
(139, 'MR', 'Mauritania'),
(140, 'MU', 'Mauritius'),
(141, 'TY', 'Mayotte'),
(142, 'MX', 'Mexico'),
(143, 'FM', 'Micronesia, Federated States of'),
(144, 'MD', 'Moldova, Republic of'),
(145, 'MC', 'Monaco'),
(146, 'MN', 'Mongolia'),
(147, 'ME', 'Montenegro'),
(148, 'MS', 'Montserrat'),
(149, 'MA', 'Morocco'),
(150, 'MZ', 'Mozambique'),
(151, 'MM', 'Myanmar'),
(152, 'NA', 'Namibia'),
(153, 'NR', 'Nauru'),
(154, 'NP', 'Nepal'),
(155, 'NL', 'Netherlands'),
(156, 'AN', 'Netherlands Antilles'),
(157, 'NC', 'New Caledonia'),
(158, 'NZ', 'New Zealand'),
(159, 'NI', 'Nicaragua'),
(160, 'NE', 'Niger'),
(161, 'NG', 'Nigeria'),
(162, 'NU', 'Niue'),
(163, 'NF', 'Norfolk Island'),
(164, 'MP', 'Northern Mariana Islands'),
(165, 'NO', 'Norway'),
(166, 'OM', 'Oman'),
(167, 'PK', 'Pakistan'),
(168, 'PW', 'Palau'),
(169, 'PS', 'Palestine'),
(170, 'PA', 'Panama'),
(171, 'PG', 'Papua New Guinea'),
(172, 'PY', 'Paraguay'),
(173, 'PE', 'Peru'),
(174, 'PH', 'Philippines'),
(175, 'PN', 'Pitcairn'),
(176, 'PL', 'Poland'),
(177, 'PT', 'Portugal'),
(178, 'PR', 'Puerto Rico'),
(179, 'QA', 'Qatar'),
(180, 'RE', 'Reunion'),
(181, 'RO', 'Romania'),
(182, 'RU', 'Russian Federation'),
(183, 'RW', 'Rwanda'),
(184, 'KN', 'Saint Kitts and Nevis'),
(185, 'LC', 'Saint Lucia'),
(186, 'VC', 'Saint Vincent and the Grenadines'),
(187, 'WS', 'Samoa'),
(188, 'SM', 'San Marino'),
(189, 'ST', 'Sao Tome and Principe'),
(190, 'SA', 'Saudi Arabia'),
(191, 'SN', 'Senegal'),
(192, 'RS', 'Serbia'),
(193, 'SC', 'Seychelles'),
(194, 'SL', 'Sierra Leone'),
(195, 'SG', 'Singapore'),
(196, 'SK', 'Slovakia'),
(197, 'SI', 'Slovenia'),
(198, 'SB', 'Solomon Islands'),
(199, 'SO', 'Somalia'),
(200, 'ZA', 'South Africa'),
(201, 'GS', 'South Georgia South Sandwich Islands'),
(202, 'ES', 'Spain'),
(203, 'LK', 'Sri Lanka'),
(204, 'SH', 'St. Helena'),
(205, 'PM', 'St. Pierre and Miquelon'),
(206, 'SD', 'Sudan'),
(207, 'SR', 'Suriname'),
(208, 'SJ', 'Svalbard and Jan Mayen Islands'),
(209, 'SZ', 'Swaziland'),
(210, 'SE', 'Sweden'),
(211, 'CH', 'Switzerland'),
(212, 'SY', 'Syrian Arab Republic'),
(213, 'TW', 'Taiwan'),
(214, 'TJ', 'Tajikistan'),
(215, 'TZ', 'Tanzania, United Republic of'),
(216, 'TH', 'Thailand'),
(217, 'TG', 'Togo'),
(218, 'TK', 'Tokelau'),
(219, 'TO', 'Tonga'),
(220, 'TT', 'Trinidad and Tobago'),
(221, 'TN', 'Tunisia'),
(222, 'TR', 'Turkey'),
(223, 'TM', 'Turkmenistan'),
(224, 'TC', 'Turks and Caicos Islands'),
(225, 'TV', 'Tuvalu'),
(226, 'UG', 'Uganda'),
(227, 'UA', 'Ukraine'),
(228, 'AE', 'United Arab Emirates'),
(229, 'GB', 'United Kingdom'),
(230, 'US', 'United States'),
(231, 'UM', 'United States minor outlying islands'),
(232, 'UY', 'Uruguay'),
(233, 'UZ', 'Uzbekistan'),
(234, 'VU', 'Vanuatu'),
(235, 'VA', 'Vatican City State'),
(236, 'VE', 'Venezuela'),
(237, 'VN', 'Vietnam'),
(238, 'VG', 'Virgin Islands (British)'),
(239, 'VI', 'Virgin Islands (U.S.)'),
(240, 'WF', 'Wallis and Futuna Islands'),
(241, 'EH', 'Western Sahara'),
(242, 'YE', 'Yemen'),
(243, 'ZR', 'Zaire'),
(244, 'ZM', 'Zambia'),
(245, 'ZW', 'Zimbabwe');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `apps_countries`
--
ALTER TABLE `apps_countries`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `apps_countries`
--
ALTER TABLE `apps_countries`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=246;





index.php



<!DOCTYPE html>
<html>
  <head>
    <title>Vue.js Autocomplete Textbox with PHP Mysql</title>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  </head>
  <body>
    <br />
    <br />
    <div class="container" id="autocomplete_app">
      <h3 align="center">Vue.js Autocomplete Textbox with PHP Mysql</h3>
      <br />
      <br />
      <br />
      <div class="row">
        <div class="col-md-3">

        </div>
        <div class="col-md-6">
          <auto-complete></auto-complete>
        </div>
        <div class="col-md-3">

        </div>
      </div>
    </div>
  </body>
</html>

<script>

  Vue.component('auto-complete', {
    template:`
    <div>
      <input type="text" placeholder="Enter Country name..." v-model="query" @keyup="getData()" autocomplete="off" class="form-control input-lg" />
      <div class="panel-footer" v-if="search_data.length">
        <ul class="list-group">
          <a href="#" class="list-group-item" v-for="data1 in search_data" @click="getName(data1.country_name)">{{ data1.country_name }}</a>
        </ul>
      </div>
    </div>
    `,
    data:function(){
      return{
        query:'',
        search_data:[]
      }
    },
    methods:{
      getData:function(){
        this.search_data = [];
        axios.post('fetch.php', {
          query:this.query
        }).then(response => {
          this.search_data = response.data;
        });
      },
      getName:function(name){
        this.query = name;
        this.search_data = [];
      }
    }
  });

  var application = new Vue({
    el:'#autocomplete_app'
  });

</script>


fetch.php



<?php

//fetch.php;

$connect = new PDO("mysql:host=localhost; dbname=testing", "root", "");

$received_data = json_decode(file_get_contents("php://input"));

$data = array();

if($received_data->query != '')
{
 $query = "
 SELECT country_name FROM apps_countries 
 WHERE country_name LIKE '%".$received_data->query."%' 
 ORDER BY country_name ASC 
 LIMIT 10
 ";

 $statement = $connect->prepare($query);

 $statement->execute();

 while($row = $statement->fetch(PDO::FETCH_ASSOC))
 {
  $data[] = $row;
 }
}

echo json_encode($data);

?>



Tuesday, 2 June 2020

Sending an Email with Users Own SMTP Settings in Laravel

Sending an Email with Users Own SMTP Settings in Laravel

One of the most common features that every web app offers is sending emails. Some sites make use of their email feature to send newsletters, some utilize it for gathering feedbacks. Websites that are PHP-powered make the Mail() method for email sending.

Nonetheless, the security in this case is often jeopardized since this is unfortunately not the most secure way of sending and receiving emails. To send emails in the Laravel framework, it provides numerous advanced features.

With various available packages in the market, integration of the emailing functionality becomes effortless. Laravel developers could help eCommerce brands in simplifying the email sending process through creating effective solutions.

Why Laravel for sending Emails?


Laravel provides different tools for configuring website emails. Some of the options are the following:
  • Laravel offers email queueing options
  • It proposes the use of drivers for Mailgun, SMTP, Amazon SES, SparkPost, as well as sendmail
  • File attachment of various formats, like PDF, JPEG, and other with the framework’s Templating system, enabling you to use different templates and configuring the view.
  • Markdown support could be used to build amazing templates, such as panels or buttons and many more.

The Robust Laravel Framework


Laravel is a sturdy and robust framework of MVC PHP aimed to empower developers looking for an elegant and seamless toolkit, which helps develop web apps that are full-featured. Laravel developers deliver business solutions that are exquisitely simple, easing the coding of app further.

Considered as one the most renowned frameworks of PHP for many reasons, the framework for eCommerce business provides an entire list of features, as well as other measures for convenience, a critical factor in the field of web application development.

Moreover, the Laravel framework also offers codes separation, a dedicated dependency manager, routing services, unit testing, modular packaging and numerous ways of gaining relational databases, as well as all the provisions that drive the business popularity of the framework further.

Sending Emails of Users with their own SMTP Laravel Settings


There’s a method for users to send email with their own SMTP credential. The goal is to provide a more personal look and touch to all outgoing emails and make it appear as if it directly came from a company, against a generic one for web application.

eCommerce businesses engaging the services of a Laravel development company would want to make emailing features simple and easy for their clientele. Sending quick emails in a project is possible by setting up the environment variables with valid SMTP credentials.

The Tutorial


Let me discuss in this tutorial the way to configure the applications of Laravel for sending emails using your own Gmail account, since the Gmail SMTP server with the default SMTP configurations of the framework. It could not be over emphasized, the benefits of the SMTP server. You could send email from a local server with the SMTP server.

On its own local server, it provides an ability of testing the functionality of email. Mails sent via the SMTP would not be flagged by Gmail as SPAM, as seen in mails sent with the PHP platform’s default mail function.

Let’s follow these simple steps to get started:


Step One: Configuring the Gmail SMTP Server in a Laravel App


Laravel makes use of config/mail.php file to store the used details in sending mail. The file has settings, such as MAIL_HOST, MAIL_DRIVER and MAIL_PORT and others. To successfully send an email, these information should be provided.

To add the information required, we have to edit the config/mail.php file instead of supplying details in the env.file correspondingly. So, open the env.file located in your app’s root directory and checkout the following settings:


MAIL_DRIVER=
MAIL_HOST=
MAIL_PORT=
MAIL_USERNAME=
MAIL_PASSWORD=
MAIL_ENCRYPTION=



Edit the above details as follows.


MAIL_DRIVER=smtp
MAIL_HOST=smtp.googlemail.com
MAIL_PORT=465
MAIL_USERNAME=ENTER_YOUR_EMAIL_ADDRESS(GMAIL)
MAIL_PASSWORD=ENTER_YOUR_GMAIL_PASSWORD
MAIL_ENCRYPTION=ssl





In the settings above, the MAIL_DRIVER as smtp we have configured, MAIL_HOST for Gmail as smtp.googlemail.com, MAIL_ENCRYPTION method as ssl and MAIL_PORT for the Gmail as 465.

You must replace the MAIL_USERENAME and the PASSWORD with the Gmail email add and the password respectively. Because we’re using the Gmail SMTP, we have to change several security settings on our Google account, to provide access to apps that are less secured.

Step Two: Configuring the Google Account


Login to the Google email account and then click on the Google Account button. This button is displayed when clicking on your profile pic in the Gmail Dashboard, as shown below.

Sending an Email with Users Own SMTP Settings in Laravel

When you reach the My Account Page, click on the Security, then scroll to the bottom and you would see the ‘Less secure application access’ settings. Click on the radio button to set it to ON mode.


Step Three: Email sending from your Laravel App


All the basic setup process at this point has been accomplished. Now, we can proceed to write a few Laravel PHP codes for sending an email. To begin, create a controller of your choice in which the sending mail logic would be handled. Then, write your codes in this controller with the below snippet as your guide:


$to_name = ‘RECEIVER_NAME’;
$to_email = ‘RECEIVER_EMAIL_ADDRESS’;
$data = array(‘name’=>”Ogbonna Vitalis(sender_name)”, “body” => “A test mail”);
Mail::send(‘emails.mail’, $data, function($message) use ($to_name, $to_email) {
$message->to($to_email, $to_name)
->subject(Laravel Test Mail’);
$message->from(‘SENDER_EMAIL_ADDRESS’,’Test Mail’);
});



We utilize our mail template in the code above as file 'email.mail' so we must create 'emails' folder and a mail.blade.php file at resources\views\emails\mail.blade.php

There should be various test codes to the test mail template mail.blade.php, the same as what’s you see below.


Hello <strong>{{ $name }}</strong>,
<p>{{body}}</p>



And with that, we are done. Creating any route of choice and star sending emails from your Laravel application could be done seamlessly.

The Top Laravel Emailing Tools


There are numerous email sources and packages available for the Laravel framework. Some of the most commonly used tools for sending emails are the following:
  1. Mailgun
  2. Mailtrap
  3. Swiftmailer
  4. Mandrill
  5. Sendgrid
  6. Mailchimp

Conclusion


We the setup we created, we could send emails with configured custom credentials during runtime. What’s great is that we don’t see the need to reach out to any packages that solve the particular concern. We further utilized similar orchestration and objects used by the framework under the hood for email sending.

With the use of pre-built tools, sending emails in a Laravel app is easy and fast. Moreover, as we have mentioned above, the process of integration is quite straightforward, thus developers could get started with the Laravel emailing tools swiftly.



Author Bio:


Olivia Diaz is working at eTatvaSoft, an Enterprise level Web & Mobile Application Development Company. Being a tech geek, she keeps a close watch over the industry focusing on the latest technology news and gadgets. Follow me on Twitter.

Friday, 29 May 2020

Add CSV Excel Export Button in Laravel Yajra Datatable



This is one more post on Yajra Laravel Datatables package and in this post, we will learn How to add export buttons to Yajra Laravel Datatables package. If you are using Laravel framework as your web application development task. So, in Laravel framework if you want to use jQuery Datatable plugin for display data on web page in tabular format with searching of data, pagination and data sorting feature. For all those things you have to use Yajra Datatables package in Laravel framework. By using this package you can perform server-side processing of searching, sorting and pagination of data without writing any line of code.

So, If you want to export Yajra DataTable data in excel or csv file format, then you have to add csv and excel export button in your DataTable. In Laravel framework, Yajra Datatables package has provide DataTable Buttons plugin for add export button in your Laravel Datatable. After adding of export button, you can easily export your Laravel DataTable data to CSV file or Excel sheet file format without writing any line of code. So, If want to learn How to add export button in Yajra Laravel Datatable, then you have to follow below step. After following below steps you can easily integrate csv excel export button with your Yajra Laravel Datatable and you can simply export your datatable data in csv or excel file format.

  1. Download Latest Version of Laravel Framework
  2. Make MySql Database Connection
  3. Generate Fake Data
  4. Install Yajra DataTables Package
  5. Create DataTable Class
  6. Create Controller Class
  7. Create View Blade File
  8. Set Route
  9. Run Laravel Application



1 - Download Latest Version of Laravel Framework


First we have to download latest version of Laravel framework, So If you have use window OS then you have to go command prompt in which Composer application must be installed and then after write following command.


composer create-project --prefer-dist laravel/laravel export


This command will make export folder in define directory, download and install latest version of Laravel framework.

2 - Make MySql Database Connection


After downloading of Laravel framework, first want to make database connection. For this we have to open Laravel framework .env file and in that file we have to define Mysql database configuration.


DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=testing
DB_USERNAME=root
DB_PASSWORD=


3 - Generate Fake Data


After making of Mysql Database connection, now we want to make table in mysql databaes connection and then after we want to fill that table with fake data. For this we have to follow following steps.

  • Create Model Class
  • Migrate Table Defination to Database
  • Create Factory Class
  • Create Seed Class

Create Model Class


Here we will use Model class for perform database related operation. For this, we have to create model class file. For this we have to go command prompt and write following command.


php artisan make:model Export -m


This command will make Export.php model class file in app folder. In this file we have to define table column name which you can find below.

app/Export.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Export extends Model
{
    protected $fillable = ['firstName', 'lastName'];
}



Migrate Table Defination to Database


When we have create model class, then at that time that model class migration table file has been created in database/migrations folder. In that file, we have to define table column defination which you can seen below.


<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateExportsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('exports', function (Blueprint $table) {
            $table->id();
            $table->string('firstName');
            $table->string('lastName');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('exports');
    }
}



After define table defination, now we want to migrate this table defination to mysql database and create exports table. For this we have go to command prompt and write following command.


php artisan migrate


Above command will make exports table in Mysql database. So, this way we can create table in mysql database from Laravel our laravel application.

Create Factory Class


For generate fake data and fill mysql exports table with fill data, we have to create one factory class. This class will allowed you to build fake data for your modelds. For create model factories, we have to go command prompt and write following command.


php artisan make:factory ExportFactory


This command will create model factories with name ExportFactory.php in database/factories folder. In this file, first we have import our model class and then after we have to define in which mysql table column we have to define fake data column name which can find below.

database/factories/ExportFactory.php

<?php

/** @var \Illuminate\Database\Eloquent\Factory $factory */

use App\Model;
use Faker\Generator as Faker;
use App\Export;

$factory->define(App\Export::class, function (Faker $faker) {
    return [
        'firstName'  => $faker->firstName,
        'lastName'  => $faker->lastName
    ];
});



Create Seed Class


In Laravel Seed classes is used for seeding your database with test data. In Laravel framework all seed classes has been store in database/seeds folder. For create seed class, we have to command prompt and write following command.


php artisan make:seeder ExportTableSeeder


This command will create ExportTableSeeder.php seed class in database/seeds directory. In this class first we want to import our model class then after in this class you can find run() and under this method we can define how many number of fake data has been genrated by using model factory class. You can find source below it.

database/seeds/ExportTableSeeder.php

<?php

use Illuminate\Database\Seeder;
use App\Export;

class ExportTableSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        $count = 500;
        factory(Export::class, $count)->create();

    }
}



After this we have to open database/seeds/DatabaseSeeder.php file which is already created under this database/seeds directory. So we have to open this file and under this file we can find run() method and under that method we have to called ExportTableSeeder class.

database/seeds/DatabaseSeeder.php

<?php

use Illuminate\Database\Seeder;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
        // $this->call(UserSeeder::class);
        $this->call(ExportTableSeeder::class);
    }
}



After this for generate fake data, we have to go command prompt and write following command.


composer dump-autoload


This command will regenerates the list of all classed which we have included in this Laravel project. Running of this command is required for generate fake data. And lastly for generate fake data we have to run following command.


php artisan db:seed


This command will seed your test data and it will fill exports mysql table with fake data. So, this is complete step by step process for creating fake data in Laravel framework.




4 - Install Yajra DataTables Package & DataTables Buttons plugin


Here we have use Yajra Datatables package has been used for load data in jQuery Datatable plugin in Laravel framework. For use Yajra Datatable package, we have to install in Laravel framework. For this we have go to command prompt and write following command.


composer require yajra/laravel-datatables-oracle


This command will download and install in latest version of Yajra DataTable package in Laravel framework. Here we want to add export button in Yajra Laravel Datatable, for this we have to download and intall Datatable Button plugin. For this we have to go command prompt and write followng command.


composer require yajra/laravel-datatables-buttons


This command will download and install DataTables Button plugin of Yajra Datatable package. By using this plugin we can add export button Yajra DataTables for export data for Datatable. Now we want to yajra datatable package service in Laravel framework. For this we have to open config/app.php file and under this file in provider array we have to define this two package service, which you can see below.

config/app.php

<?php

return [

    'providers' => [
      
     ---------------
        
        Yajra\DataTables\DataTablesServiceProvider::class,
        Yajra\DataTables\ButtonsServiceProvider::class,

      ---------------

    ],
];



After defining of service, now we want to publish DataTable Button service, for this we have go to command prompt and write following command.


php artisan vendor:publish --tag=datatables-buttons


This command will publish datatables buttons plugin service in Laravel. Now we can use datatables buttons in Laravel framework for add export button Datatable.

5 - Create DataTable Class


In this tutorial, we will use DataTable class for load data in jQuery Datatable plugin and add export button in DataTable for export data in CSV or Excel file. For this we have to create DataTable class, for this we have go to command prompt and write following command.


php artisan datatables:make ExportDataTable


This command will make DataTables/ExportDataTable.php class file in app directory. So, we have to open this file, and in this class file we have to import model class. In this class file, we can see following method.

dataTable($query) - This method will build DataTable class.
query(ExportDataTable $model) - This method is used for get the query source of DataTable. In this method we have define data fetch query.
html() - This method will build your html code and Ajax jQuery script for initialize jQuery Datatable plugin. In this method we can define which export button you want to add in Datatable.
getColumns() - In this method we have to define Mysql table column name.
filename() - This method is used for get the file name for export.

app/DataTables/ExportDataTable.php

<?php

namespace App\DataTables;

use App\Export;
use App\DataTables\ExportDataTable;
use Yajra\DataTables\Html\Button;
use Yajra\DataTables\Html\Column;
use Yajra\DataTables\Html\Editor\Editor;
use Yajra\DataTables\Html\Editor\Fields;
use Yajra\DataTables\Services\DataTable;

class ExportDataTable extends DataTable
{
    /**
     * Build DataTable class.
     *
     * @param mixed $query Results from query() method.
     * @return \Yajra\DataTables\DataTableAbstract
     */
    public function dataTable($query)
    {
        return datatables()
            ->eloquent($query);
    }

    /**
     * Get query source of dataTable.
     *
     * @param \App\ExportDataTable $model
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function query(ExportDataTable $model)
    {
        //return $model->newQuery();
        $data = Export::select();
        return $this->applyScopes($data);
    }

    /**
     * Optional method if you want to use html builder.
     *
     * @return \Yajra\DataTables\Html\Builder
     */
    public function html()
    {
        return $this->builder()
                    ->columns($this->getColumns())
                    ->minifiedAjax()
                    ->dom('Bfrtip')
                    ->orderBy(1)
                    ->buttons(
                        Button::make('csv'),
                        Button::make('excel')
                    );
    }

    /**
     * Get columns.
     *
     * @return array
     */
    protected function getColumns()
    {
        return [
            Column::make('id'),
            Column::make('firstName'),
            Column::make('lastName'),
            Column::make('created_at'),
            Column::make('updated_at'),
        ];
    }

    /**
     * Get filename for export.
     *
     * @return string
     */
    protected function filename()
    {
        return 'Export_' . date('YmdHis');
    }
}



6 - Create Controller Class


In Laravel framework for handle http request, we have to ceate Controller class. In Laravel framework controller class file has been store in app/Http/Controllers follder. For create controller class file, we have to go command prompt and write following command.


php artisan make:controller ExportController


This command will create ExportController.php controller class file. In this file, first we want to import ExportDataTable.php class and then after we have to make index method which will render ExportDataTable class data and load in export.blade.php view file.

app/Http/Controllers/ExportController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\DataTables\ExportDataTable;

class ExportController extends Controller
{
    public function index(ExportDataTable $dataTable)
    {
     return $dataTable->render('export');
    }
}



7 - Create View Blade File


For display output in Laravel framework, it has been used blade templating engine for display HTML output in browser. In Laravel framework view files has been store in resources/views folder. In this directory we have already create export.blade.php file. This file will display Mysql table data in DataTable by using Yajra Datatable package. And with data you can also find export csv or excel button also.

resources/views/export.blade.php

<html>
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Add CSV Excel Export Button in Yajra Laravel Datatable</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
    <script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>  
    <link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css" />
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    <link rel="stylesheet" href="https://cdn.datatables.net/buttons/1.0.3/css/buttons.dataTables.min.css">
    <script src="https://cdn.datatables.net/buttons/1.0.3/js/dataTables.buttons.min.js"></script>
    <script src="{{ asset('vendor/datatables/buttons.server-side.js') }}"></script>
  </head>
  <body>
    <div class="container">    
      <br />
      <h3 align="center">Add CSV Excel Export Button in Yajra Laravel Datatable</h3>
      <br />
      <div class="table-responsive">
        <div class="panel panel-default">
          <div class="panel-heading">Sample Data</div>
          <div class="panel-body">
            
            {!! $dataTable->table() !!}

            {!! $dataTable->scripts() !!}
          </div>
        </div>        
      </div>
      <br />
      <br />
    </div>
  </body>
</html>



8 - Set Route


In next we want to set the route of controller class method. For set route we have to open routes/web.php file and in this file we have to define route which you can find below.

routes/web.php


Route::resource('export', 'ExportController');



9 - Run Laravel Application


Now all set and we are ready to check output in browser. But before check output in browser, we have to first start Laravel application server. For this we have go to command prompt and write following command.


php artisan serve


This command will start Laravel server and provide base url of Laravel application. For test above code we have to write following url.


http://127.0.0.1:8000/export


So this is step by step processing of How to add export button in Laravel Yajra DataTable package. In this tutorial, we have first learn How to generate fake data in Laravel and then after we have seen how to load data in Datatable in Laravel framework by using Yajra Datatable package and then after we have seen how can we export Yajra DataTable data in CSV or Excel file format by using Yajra DataTable buttons plugin. So If you have found this tutorial helpful to you then do not forget to share it.