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.

Friday, 22 May 2020

Check Username or Email Availability using Vue.js with PHP



In this Vue.js tutorial, we will make PHP script for implement username or email live check for registration feature using Vue.js with Axios package for send Ajax request. This functionality is very common and it is required feature for most of the websites which is available online. If in your website, you have give login rights to user by entering their username or email and password, and get access into websites. Then at that time their username or email address must be unique. For this things when user has come into your websites for new account registration, then at that time we have to check username or email is available for registration or not for prevent duplicate registration with same username or email address.

For this problem, In this tutorial, we will use Vue.js with PHP script for check username of email already exists in our Mysql database or not. If Username or email is already exists then at that time we have stop user registration process by displaying message like particular email or username is already registered in our system try with different username or email address, and it will notify to the user regarding email address or username is already used by some another person before submitting of registration form data. Now in your mind one question will arise, how to check email ID or username exist or not in database, for this we will use Ajax with Vue.js and PHP script. When user has type something in username or email textbox then Vue.js will send Ajax request to PHP script with query like for search particular username or email address already exists in Mysql database.

This we can done when User has create account in our website, so while user enters their username or email id then Vue.js will triggered Ajax call and it will send request to PHP script at server side to check the availability status of email address or username. At PHP script, it will matches user data which they have enter with data available in Mysql database and it will send back response to Ajax request with availability of Username or email address which will be display on web page by using Vue.js without refresh of web page. So checking of availability of Email Address or Username of the user at the time registration is the best way to prevent duplicate registration in our web application. So from this tutorial, you can learn how to check email id or username availability of user from database, this things here we will use Ajax with Vue.js and PHP script. Below you can find the complete source code of how to check availability of the username or email address using ajax and Vue.js in PHP.


Check Username or Email Availability using Vue.js with PHP




Source Code


Mysql Database



--
-- Database: `testing`
--

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

--
-- Table structure for table `tbl_login`
--

CREATE TABLE `tbl_login` (
  `id` int(11) NOT NULL,
  `first_name` varchar(100) NOT NULL,
  `last_name` varchar(100) NOT NULL,
  `gender` varchar(30) NOT NULL,
  `email` varchar(200) NOT NULL,
  `password` varchar(200) NOT NULL,
  `address` text NOT NULL,
  `mobile_no` varchar(15) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `tbl_login`
--

INSERT INTO `tbl_login` (`id`, `first_name`, `last_name`, `gender`, `email`, `password`, `address`, `mobile_no`) VALUES
(1, 'John', 'Smith', 'male', 'johnsmith@gmail.com', '$2y$10$vgo3NI5w5cLB74E4B2sdVuKwdSpJL/EAeKSUdevkc/j3zl0sJAf5i', 'test address', '9632587410');

--
-- Indexes for dumped tables
--

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

--
-- AUTO_INCREMENT for dumped tables
--

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





index.php



<!DOCTYPE html>
<html>
 <head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Live Username Or Email Availability using Vue.js in PHP</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>
  <div class="container" id="registerApp">
   <br />
   <h3 align="center">Live Username Or Email Availability using Vue.js in PHP</h3>
   <br />
   <div class="panel panel-default">
    <div class="panel-heading">
     <h3 class="panel-title">Register</h3>
    </div>
    <div class="panel-body">
     <div class="form-group">
      <label>Enter Your Email</label>
      <input type="text" v-model="email" class="form-control input-lg" :class="class_name" @keyup="check()" />
      <span :class="[dynamic_class ? 'success' : 'danger']">{{ message }}</span>
     </div>
     <div class="form-group">
      <label>Enter Your Password</label>
      <input type="password" v-model="password" class="form-control input-lg" />
     </div>
     <div class="form-group" align="center">
      <button type="button" :disabled="is_disable" class="btn btn-info btn-lg">Register</button>
     </div>
    </div>
   </div>
  </div>
 </body>
</html>

<style>
.success
{
 font-weight: bold;
 color:#009933;
 background-color: #ccffcc;
 border:1px solid #009933;
}

.danger
{
 font-weight: bold;
 color:#ff0000;
 background-color: #ffe6e6;
 border:1px solid #ff0000;
}
</style>

<script>

var application = new Vue({
 el:'#registerApp',
 data:{
  email:'',
  dynamic_class:true,
  message:'',
  password:'',
  is_disable:false,
  class_name:''
 },
 methods:{
  check:function(){
   var email = application.email.trim();
   if(email.length > 2)
   {
    axios.post('action.php', {
     email:email
    }).then(function(response){
     if(response.data.is_available == 'yes')
     {
      application.dynamic_class = true;
      application.message = 'This Email is Available for Registration';
      application.is_disable = false;
      application.class_name = 'success';
     }
     else
     {
      application.dynamic_class = false;
      application.message = 'This Email is already registred';
      application.is_disable = true;
      application.class_name = 'danger';
     }
    });
   }
   else
   {
    application.message = '';
    application.class_name = '';
    application.dynamic_class = true;
    application.is_disable = false;
   } 
  }
 }
});

</script>


action.php



<?php

//action.php

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

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

$data = array();

if($received_data->email != '')
{
 $is_available = 'yes';

 $query = "
 SELECT * FROM tbl_login 
 WHERE email = '".$received_data->email."'
 ";

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

 $statement->execute();

 $total_row = $statement->rowCount();

 if($total_row > 0)
 { 
  $is_available = 'no';
 }

 $data = array(
  'is_available'  => $is_available
 );
}

echo json_encode($data);

?>


If you like this tutorial and you have found that this tutorial helpful then please don't forget to share this tutorial.

Sunday, 17 May 2020

Make Editable Datatable using jQuery Tabledit Plugin with PHP Ajax



Hey Guys Are you looking of tutorial on How can we use jQuery Datatable plugin and jQuery Tabledit plugin together in PHP application by using Ajax. If yes, then you have come on the right page, because in this tutorial, we have will describe you step by step how can we use jQuery Tabledit plugin with Datatable plugin and convert Datable grid into editable PHP grid using Ajax. In this post we will create Live Editable Datatable with jQuery Tabledit plugin using PHP script and Ajax, and in this Live Editable Datatable user can perform Mysql Edit or update data operation and delete or remove data operation by using jQuery Tabledit plugin without refresh of web page because tabledit plugin will send Ajax request to PHP script for Mysql edit or delete data operation.

In this tutorial, we have use jQuery Datatable plugin, which is very powerful jQuery plugin for creating dynamic table grid for display data on web page in tabular format. This plugin has provide functionality like searching, sorting and pagination without any configuratin. In this post we have use jQuery Datatable plugin for load mysql table data and display on web page in PHP table grid with different feature like live searching of data, table column sorting of data, pagination. This all feature will work with PHP server-side operation. This is because here we have use PHP script with jQuery Datatable plugin for fetch data from Mysql table and send back to jquery Datatable plugin in json format because here we will use Ajax for send and received data from PHP script.




Same way here we have also use one more jQuery plugin with Datatable plugin and here we have use jQuery Tabledit plugin with jQuery Datatable plugin for Inline Datatable editing and deleting with PHP script using Ajax. By using Tabledit plugin, it will convert simple html table into inline editable table with feature like live edit and delete of data. This is plugin is compatiable with Bootstrap library. If you want to create live editable table then you can use this jQuery Tabledit plugin which will send Ajax request to PHP script for edit or delete of data from database. In this tutorial, we have use tabledit plugin with jQuery Datatable for convert Datatable grid into inline editable Datatable with edit or delete Datatable data without refresh of web page. So, if you want to make Live Datatable Edit Delete mysql table data then you can use tabledit plugin with jQuery Datatable using PHP script with Ajax. This post will help you to make datatable editable by using jQuery tabledit plugin with PHP script and Ajax. Below you can find complete source code of this tutorial.



Database



--
-- Database: `testing`
--

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

--
-- Table structure for table `tbl_sample`
--

CREATE TABLE `tbl_sample` (
  `id` int(11) NOT NULL,
  `first_name` varchar(250) NOT NULL,
  `last_name` varchar(250) NOT NULL,
  `gender` enum('Male','Female') NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

--
-- Dumping data for table `tbl_sample`
--

INSERT INTO `tbl_sample` (`id`, `first_name`, `last_name`, `gender`) VALUES
(1, 'John', 'Smith', 'Male'),
(2, 'Peter', 'Parker', 'Male'),
(4, 'Donna', 'Huber', 'Male'),
(5, 'Anastasia', 'Peterson', 'Male'),
(6, 'Ollen', 'Donald', 'Male'),
(10, 'Joseph', 'Stein', 'Male'),
(11, 'Wilson', 'Fischer', 'Male'),
(12, 'Lillie', 'Kirst', 'Female'),
(13, 'James', 'Whitchurch', 'Male'),
(14, 'Timothy', 'Brewer', 'Male'),
(16, 'Sally', 'Martin', 'Male'),
(17, 'Allison', 'Pinkston', 'Male'),
(18, 'Karen', 'Davis', 'Male'),
(19, 'Jaclyn', 'Rocco', 'Male'),
(20, 'Pamela', 'Boyter', 'Male'),
(21, 'Anthony', 'Alaniz', 'Male'),
(22, 'Myrtle', 'Stiltner', 'Male'),
(23, 'Gary', 'Hernandez', 'Male'),
(24, 'Fred', 'Jeffery', 'Male'),
(25, 'Ronald', 'Stjohn', 'Male'),
(26, 'Stephen', 'Mohamed', 'Male'),
(28, 'Michael', 'Dyer', 'Male'),
(29, 'Betty', 'Beam', 'Male'),
(30, 'Anna', 'Peterson', 'Female'),
(31, 'Peter', 'Stodola', 'Male'),
(32, 'Ralph', 'Jones', 'Male');

--
-- Indexes for dumped tables
--

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

--
-- AUTO_INCREMENT for dumped tables
--

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





database_connection.php



<?php

//database_connection.php

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

?>


index.php



<html>
 <head>
  <title>How to use Tabledit plugin with jQuery Datatable in PHP Ajax</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>
  <script src="https://markcell.github.io/jquery-tabledit/assets/js/tabledit.min.js"></script>
 </head>
 <body>
  <div class="container">
   <h3 align="center">How to use Tabledit plugin with jQuery Datatable in PHP Ajax</h3>
   <br />
   <div class="panel panel-default">
    <div class="panel-heading">Sample Data</div>
    <div class="panel-body">
     <div class="table-responsive">
      <table id="sample_data" class="table table-bordered table-striped">
       <thead>
        <tr>
         <th>ID</th>
         <th>First Name</th>
         <th>Last Name</th>
         <th>Gender</th>
        </tr>
       </thead>
       <tbody></tbody>
      </table>
     </div>
    </div>
   </div>
  </div>
  <br />
  <br />
 </body>
</html>

<script type="text/javascript" language="javascript" >
$(document).ready(function(){

 var dataTable = $('#sample_data').DataTable({
  "processing" : true,
  "serverSide" : true,
  "order" : [],
  "ajax" : {
   url:"fetch.php",
   type:"POST"
  }
 });

 $('#sample_data').on('draw.dt', function(){
  $('#sample_data').Tabledit({
   url:'action.php',
   dataType:'json',
   columns:{
    identifier : [0, 'id'],
    editable:[[1, 'first_name'], [2, 'last_name'], [3, 'gender', '{"1":"Male","2":"Female"}']]
   },
   restoreButton:false,
   onSuccess:function(data, textStatus, jqXHR)
   {
    if(data.action == 'delete')
    {
     $('#' + data.id).remove();
     $('#sample_data').DataTable().ajax.reload();
    }
   }
  });
 });
  
}); 
</script>


fetch.php



<?php

//fetch.php

include('database_connection.php');

$column = array("id", "first_name", "last_name", "gender");

$query = "SELECT * FROM tbl_sample ";

if(isset($_POST["search"]["value"]))
{
 $query .= '
 WHERE first_name LIKE "%'.$_POST["search"]["value"].'%" 
 OR last_name LIKE "%'.$_POST["search"]["value"].'%" 
 OR gender LIKE "%'.$_POST["search"]["value"].'%" 
 ';
}

if(isset($_POST["order"]))
{
 $query .= 'ORDER BY '.$column[$_POST['order']['0']['column']].' '.$_POST['order']['0']['dir'].' ';
}
else
{
 $query .= 'ORDER BY id DESC ';
}
$query1 = '';

if($_POST["length"] != -1)
{
 $query1 = 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
}

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

$statement->execute();

$number_filter_row = $statement->rowCount();

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

$statement->execute();

$result = $statement->fetchAll();

$data = array();

foreach($result as $row)
{
 $sub_array = array();
 $sub_array[] = $row['id'];
 $sub_array[] = $row['first_name'];
 $sub_array[] = $row['last_name'];
 $sub_array[] = $row['gender'];
 $data[] = $sub_array;
}

function count_all_data($connect)
{
 $query = "SELECT * FROM tbl_sample";
 $statement = $connect->prepare($query);
 $statement->execute();
 return $statement->rowCount();
}

$output = array(
 'draw'   => intval($_POST['draw']),
 'recordsTotal' => count_all_data($connect),
 'recordsFiltered' => $number_filter_row,
 'data'   => $data
);

echo json_encode($output);

?>


action.php



<?php

//action.php

include('database_connection.php');

if($_POST['action'] == 'edit')
{
 $data = array(
  ':first_name'  => $_POST['first_name'],
  ':last_name'  => $_POST['last_name'],
  ':gender'   => $_POST['gender'],
  ':id'    => $_POST['id']
 );

 $query = "
 UPDATE tbl_sample 
 SET first_name = :first_name, 
 last_name = :last_name, 
 gender = :gender 
 WHERE id = :id
 ";
 $statement = $connect->prepare($query);
 $statement->execute($data);
 echo json_encode($_POST);
}

if($_POST['action'] == 'delete')
{
 $query = "
 DELETE FROM tbl_sample 
 WHERE id = '".$_POST["id"]."'
 ";
 $statement = $connect->prepare($query);
 $statement->execute();
 echo json_encode($_POST);
}


?>

Sunday, 10 May 2020

How to Update Delete Table row with jQuery Tabledit in Laravel


Are you looking for tutorial on Live Table Edit Delete Mysql Data using Tabledit Plugin in Laravel. So you have come on right post, because in this tutorial we have make discussion on How to integrate jQuery Tabledit plugin in Laravel framework.


We all know Live HTML table edit and delete or Inline table edit delete is very user freindly functionality and by this feature user can change or remove table row value by clicking on edit or delete button. In this tutorial, We will learn How to make live or inline editable HTML table with jQuery and Laravel framework. For this things, we will use Tabledit jQuery plugin, and that plugin will provide Ajax request for inline edit or delete table row data. This plugin will convert simple HTML into Inline editable table, so you user can make easily change or edit table cell value, or even User can also delete or remove table row data also.


Here we will learn How to integrate jQuery Tabledit plugin with Laravel framework. Here we will seen How can we apply jQuery Tabledit plugin functionality like inline editing or removing functionality on HTML table and it will use Ajax request for inline or live edit or delete Mysql data operation and in backend we will use Laravel framework. This plugin is compatible with Bootstrap 3 and Bootstrap 4 library. We all know Laravel is robust PHP framework for web application development, so if you want to build live inline table edit or delete application in Laravel framework, then you should use tabledit plugin for this feature. For this here we have make this tutorial, and below you can find step by step process for integrate Tabledit plugin in Laravel framework.


How to Update Delete Table row with jQuery Tabledit in Laravel





  1. Download Laravel Framework
  2. Make Database Connection
  3. Create Controller
  4. Create View Blade File
  5. Ret Controller Method Route
  6. Run Laravel Application




1 - Download Laravel Framework


If you want to make any web application in Laravel framework, then first we have to download Laravel framework and install in our local computer. For this we have to go command prompt, and first run composer command. After this we have go to directory or folder in which we want to download Laravel latest vesion and run following command.



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


This command will make laravel7 folder and in that folder it will download the latest version of Laravel framework.


2 - Make Database Connection


Once Laravel latest copy has been download, so in next step we want to make database connection. Here we want to make Mysql database connection, for this we have open .env file and in that file we have define Mysql database configuration.



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


After making database connection in Laravel framework, now we want to make table in mysql database. For this run following SQL script in your local phpmyadmin. It will make sample_datas table in your local database.



--
-- Database: `testing`
--

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

--
-- Table structure for table `sample_datas`
--

CREATE TABLE `sample_datas` (
  `id` bigint(20) UNSIGNED NOT NULL,
  `first_name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `last_name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `gender` enum('Male','Female') COLLATE utf8mb4_unicode_ci NOT NULL,
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

--
-- Dumping data for table `sample_datas`
--

INSERT INTO `sample_datas` (`id`, `first_name`, `last_name`, `gender`, `created_at`, `updated_at`) VALUES
(78, 'Johny', 'Smith', 'Male', '2019-10-11 21:39:09', '2019-10-11 21:39:09'),
(80, 'Larry', 'Degraw', 'Female', '2019-10-11 21:39:09', '2019-10-11 21:39:09'),
(81, 'Susan', 'Diener', 'Female', '2019-10-14 00:30:00', '2019-10-14 00:30:00'),
(82, 'William', 'Batiste', 'Male', '2019-10-14 00:30:00', '2019-10-14 00:30:00'),
(83, 'Butler', 'Tucker', 'Male', '2019-10-14 00:30:00', '2019-10-19 03:24:32'),
(84, 'Eva', 'King', 'Male', '2019-10-14 00:30:00', '2019-10-14 00:30:00'),
(85, 'Dorothy', 'Hays', 'Male', '2019-10-14 03:30:00', '2019-10-14 03:30:00'),
(86, 'Nannie', 'Ayers', 'Male', '2019-10-14 03:30:00', '2019-10-14 03:30:00'),
(87, 'Gerald', 'Brown', 'Male', '2019-10-14 04:30:00', '2019-10-14 04:30:00'),
(88, 'Judith', 'Smith', 'Male', '2019-10-14 04:30:00', '2019-10-14 04:30:00'),
(89, 'Delores', 'Schumacher', 'Male', '2019-10-14 13:30:00', '2019-10-14 13:30:00'),
(90, 'Gloria', 'Romero', 'Male', '2019-10-14 06:30:00', '2019-10-14 06:30:00');

--
-- Indexes for dumped tables
--

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

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `sample_datas`
--
ALTER TABLE `sample_datas`
  MODIFY `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=96;


3 - Create Controller


In Laravel framework for handle http request, we have to make controller class in Laravel framework. In Laravel framework controller file has been store under app/Http/Controllers folder. For create new controller class file, we have to go command prompt and run following command.



php artisan make:controller TableditController


This command will make TableditController.php controller file. In this tutorial for make Live or inline table edit or delete mysql database operation, here in this controller file, we have make following method.


index() - This is the root method of this controller class. This method has been fetch data from sample_datas table and it will send this data to view file for display on web page.

action() - This method has received Ajax request for edit or delete mysql data operation. If it has received Ajax request for edit or update mysql data, then it will update or edit mysql table data, and if this method has received Ajax request for delete data operation, then it has been delete data from Mysql table.


app/Http/Controllers/TableditController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;

class TableditController extends Controller
{
    function index()
    {
    	$data = DB::table('sample_datas')->get();
    	return view('table_edit', compact('data'));
    }

    function action(Request $request)
    {
    	if($request->ajax())
    	{
    		if($request->action == 'edit')
    		{
    			$data = array(
    				'first_name'	=>	$request->first_name,
    				'last_name'		=>	$request->last_name,
    				'gender'		=>	$request->gender
    			);
    			DB::table('sample_datas')
    				->where('id', $request->id)
    				->update($data);
    		}
    		if($request->action == 'delete')
    		{
    			DB::table('sample_datas')
    				->where('id', $request->id)
    				->delete();
    		}
    		return response()->json($request);
    	}
    }
}



4 - Create View Blade File


For display HTML output in browser, here in Laravel framework it has use view blade file, which has been store in resources/views folder. In this folder we have create table_edit.blade.php file. In this file we have include jQuery, Bootstrap and Tabledit plugin library link.


In this file, we have crate one HTML table and in this table we have add one id="editable" attribute. This attribute value is used for initialize tabledit plugin by using Tabledit() method. In this plugin, we have to define table column, which we want to convert into editable cell. We can define editable cell details in editable option of Tabledit method. This method will send Ajax request to action() method of TableditController class. Below you can find complete source code of view blade file.


resources/views/table_edit.blade.php

<html>
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Live Table Edit Delete Mysql Data using Tabledit Plugin in Laravel</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://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>            
    <script src="https://markcell.github.io/jquery-tabledit/assets/js/tabledit.min.js"></script>
  </head>
  <body>
    <div class="container">
      <br />
      <h3 align="center">Live Table Edit Delete with jQuery Tabledit in Laravel</h3>
      <br />
      <div class="panel panel-default">
        <div class="panel-heading">
          <h3 class="panel-title">Sample Data</h3>
        </div>
        <div class="panel-body">
          <div class="table-responsive">
            @csrf
            <table id="editable" class="table table-bordered table-striped">
              <thead>
                <tr>
                  <th>ID</th>
                  <th>First Name</th>
                  <th>Last Name</th>
                  <th>Gender</th>
                </tr>
              </thead>
              <tbody>
                @foreach($data as $row)
                <tr>
                  <td>{{ $row->id }}</td>
                  <td>{{ $row->first_name }}</td>
                  <td>{{ $row->last_name }}</td>
                  <td>{{ $row->gender }}</td>
                </tr>
                @endforeach
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  </body>
</html>

<script type="text/javascript">
$(document).ready(function(){
   
  $.ajaxSetup({
    headers:{
      'X-CSRF-Token' : $("input[name=_token]").val()
    }
  });

  $('#editable').Tabledit({
    url:'{{ route("tabledit.action") }}',
    dataType:"json",
    columns:{
      identifier:[0, 'id'],
      editable:[[1, 'first_name'], [2, 'last_name'], [3, 'gender', '{"1":"Male", "2":"Female"}']]
    },
    restoreButton:false,
    onSuccess:function(data, textStatus, jqXHR)
    {
      if(data.action == 'delete')
      {
        $('#'+data.id).remove();
      }
    }
  });

});  
</script>



5 - Ret Controller Method Route


Once your all code is ready, then lastly, we have 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 for all controller class method.


routes/web.php

Route::get('tabledit', 'TableditController@index');

Route::post('tabledit/action', 'TableditController@action')->name('tabledit.action');


6 - Run Laravel Application


Afer setting of Route for controller class method. Now our Laravel Inline edit or delete application is ready by using jQuery Tabledit plugin. For this application, we have to go command prompt and run following command.



php artisan serve


This command will start Laravel application server and give you base URL of your Laravel application. For test above Live table edit delete Mysql data application, you have to enter following URL in your browser.



http://127.0.0.1:8000/tabledit


I hope this post will helps anyone who was looking for How to make Live or Inline update or delete table row data by using jQuery Tabledit plugin with Laravel framework.



What is the difference between PHP5 and PHP 7

What is the difference between PHP5 and PHP 7


PHP was invented in 1994 by Rasmus Lerdorf and from 1994 to 2020 this language is a very popular and suitable scripting language for all web developers, web development companies have developed many websites using PHP scripting language. PHP gives you a lot of features that are limited and useful for a web developer to build a good website. If you do not follow PHP closely or you are a beginner in PHP and want to make a career, then you can learn the course on tutorials like w3school or, udemi, php quora. PHP has brought many versions of web development from 1994 to 2020 and has also upgraded.

Many new PHP developers are not aware of the older version of version 7, so here we will discuss what is the difference between PHP7 and PHP5? And with this, there are new developers who do not have that much knowledge about PHP. So here we will talk about what is PHP and what are the new features in PHP 7.

PHP Definition


PHP means, hypertext preprocessor, PHP is a widely-used is an open-source scripting language, and PHP script is executed on the server. PHP is suitable for web development. PHP can be embedded in HTML.

What is a PHP file?


PHP files are stored as .php extensions in any folder. The PHP script is executed on the server and outputs to the web browser in HTML format. In any PHP file content is like text, HTML, CSS, JavaScript, and PHP code.

Why PHP is so important for web development?


Is PHP important to learn, because PHP is easy to learn for any PHP beginner, PHP is free downloadable from official resources (www.php.net). PHP is compatible with all servers (Apache, IIS, etc), which is the most used in today's era. PHP runs on various platforms such as Windows, Linux, UNIX, Mac OS X, etc.

What you can do with PHP


What can PHP do, PHP generates dynamic web page content, collects form data, and also accepts encrypted data. Add, delete, modify, search, and view data coming from the database. PHP can send and receive cookies and control user access.




What are the new features in PHP 7?


PHP7 is a current version of PHP, but many new beginners do not use the older version of PHP, so here we give you information about the new features in the Php7 version, and after that we will get the complete difference between PHP7 and PHP5. Let's describe. PHP7 is faster than the previous stable version (PHP5). PHP7 improves its error handling. PHP7 fully supports for new operators.

What is the difference between PHP5 and PHP 7


Why the company jumps to the php7 version after the php5 version because a company announced that php5 is a good and very stable version and is out for php6 release, but did not remain as a stable version after testing php6, And the company did not want to confuse the community. Therefore, the php7 version is declared for release after the php5 version. When you update the version many masterstroke changes are seen, then someone becomes your strength and someone becomes your weakness. So we will talk about what is the difference between PHP5 and PHP7.

1: Performance


Performance, this term is a very important masterstroke in the difference between PHP7 and PHP5. Suppose you have a code and you can run this code with both versions, at that time the php5 version gives slower output with the use of Zend ||, but php7 uses brand new PHP-NG. This model offers a good improvement in performance, and a good focus on optimizing memory usage. This cause is affecting the performance of speed. So php7 is faster than php5.

2: Declare return type PHP


In PHP5, it has a very large defect coding scenario because the developer was unable to stop the unwanted return type, and produces an exception because PHP5 does not allow the programmer to declare the return type of a function or method. The company removed this reason and added this feature to the new version PHP7. PHP7 allows developers to declare a return type of function. This concept is good for all developers and helps make the code accurate and robust.

3: Allow new Operators


In php7, we notice all new operators, such as notation and null co-operators. The notation is technically called a combined comparison or three-level comparison operator (<=>). This operator is used in sorting and various joint comparisons. This operator acts like strcmp () and qualifies to replace the library function version_compare (). And the other operator is the null coalescing operator, used to check if something exists. And the sign uses double question marks (??).

4: MySql function


The PHP version php5 supports the MySQL syntax to connect to the MySQL database, but PHP7 only supports the mysqli syntax to connect to the MYSQL database.

5: Anonymous class feature


Php5 has not provided anonymous category features in web development, even though php5 follows the object-oriented feature, and is also used in other programming languages such as Java and c #. But PHP5 lacks this feature. So this reason is resolved in the PHP 7 stable version of PHP. An anonymous class is used for faster execution times and is suitable when you do not have to execute the class more than once.

Right now all our readers and those who want to make a career in PHP have understood what is the PHP definition, what can you do with PHP, what is a PHP file ?, what are the new features in PHP 7 ? And What is the difference between PHP5 and PHP 7.