Tuesday, 20 April 2021

How to Add Custom Select Box pagination in jQuery DataTable with Ajax PHP


In this post you can find the solution of How to navigate to a specific page in jQuery DataTable with Ajax PHP. In jQuery DataTable there is pagination feature is available for go next page or previous page or first page or last page or any five number page link is available for view page data in jquery datatable but suppose there is large table with more than 1000 pages, and that data has been load in jQuery DatTable and there are multiple pagination link will be made by jQuery DataTable plugin, now we want to go to any specific page number data directly or jump to the specific page number. So at that time we want to required Select box pagination is required with DataTable default pagination. So in select box we can find list of page number. So when we want to go to specific page then we have to simply select page number, and jQuery DataTable will load that data with server-side processing using Ajax PHP.

jQuery DataTable has pagination plugin like Navigation with text input field pagination and Select list pagination plugin. So when we have use this jQuery DataTable plugin, then DataTable default pagination link has been removed and that Input textbox or Select box pagination will be display. But we want to add select box pagination with jQuery DataTable default pagination. For implement this feature, we have lots of search on internet regarding how can we have implement select box pagination with jQuery Datatable default pagination. After spend lots of time, we have to decide to make custom select box pagination in jQuery DataTable plugin. But in jquery DataTable there is not so easy to add custom select box pagination with DataTable Table pagination.

After do many research, we have found jQuery page api info() method. This page.info() api has return details of jquery DataTable page information. By this method we can get the value of current page number, length of data etc. By using this information, we have make custom select box with data. So when DataTable data has been change then it will make fill page number in select box using drawCallback function. This function will be called on every refresh of data. So After filling select box with page number data. Now we want to write simple jQuery like when we have select page number from select box, then it will execute that block of code. Under this code, it will first fetch start and length variable value from selected page option data attribute and based on this data it will load that page data in jQuery DataTable.


How to Add Custom Select Box pagination in jQuery DataTable with Ajax PHP







By this code you can implement two different type of pagination on jQuery DataTable at the same time. One is the default pagination of DataTable and other one is this custom select box pagination. So if you want to add custom select box pagination in jQuery DataTable then below source code will help you and you can add feature like navigate page to specific number of page in jQuery DataTable. This feature will help you when you have load large data in jQuery DataTable and you want to view any specific page number data. I hope you have understand this post and you have got success in implement two different type of pagination in jQuery DataTable with Ajax jQuery. Below you can find source code.



Source Code


index.php



<html>
	<head>
		<title>jQuery DataTable Jump to a Specific Page with PHP Ajax</title>
		<!-- JS, Popper.js, and jQuery -->
		<script  src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>
		<!-- CSS only -->
		<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">		
		<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
		<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script>
		<script src="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.min.js"></script>
		<script src="https://cdn.datatables.net/1.10.22/js/dataTables.bootstrap4.min.js"></script>
		<link rel="stylesheet" href="https://cdn.datatables.net/1.10.22/css/dataTables.bootstrap4.min.css" />
	</head>
	<body>
		<div class="container">
			<br />
			<h1 align="center" class="text-primary"><b>jQuery DataTable Jump to a Specific Page with PHP Ajax</b></h1>
			<br />
			<div class="card">
				<div class="card-header">
					<div class="row">
						<div class="col-md-9">Customer Data</div>
						<div class="col-md-3">
							<div class="input-group">
								<div class="input-group-prepend">
									<span class="input-group-text">Page</span>
								</div>
								<select name="pagelist" id="pagelist" class="form-control"></select>
								<div class="input-group-append">
									<span class="input-group-text">of&nbsp;<span id="totalpages"></span></span>
								</div>
							</div>
						</div>
					</div>
				</div>
				<div class="card-body">
					<div class="table-responsive">

						<table id="customer_table" class="table table-bordered table-striped">
							<thead>
								<tr>
									<th>Customer ID</th>
									<th>Customer First Name</th>
									<th>Customer Last Name</th>
									<th>Customer Email</th>
									<th>Customer Gender</th>
								</tr>
							</thead>
						</table>
						
					</div>
				</div>
			</div>
		</div>
		<br />
		<br />
	</body>
</html>

<script type="text/javascript" language="javascript">

$(document).ready(function(){

	function load_data(start, length)
	{
		var dataTable = $('#customer_table').DataTable({
			"processing" : true,
			"serverSide" : true,
			"order" : [],
			"retrieve": true,
			"ajax" : {
				url:"fetch.php",
				method:"POST",
				data:{start:start, length:length}
			},
			"drawCallback" : function(settings){
				var page_info = dataTable.page.info();

				$('#totalpages').text(page_info.pages);

				var html = '';

				var start = 0;

				var length = page_info.length;

				for(var count = 1; count <= page_info.pages; count++)
				{
					var page_number = count - 1;

					html += '<option value="'+page_number+'" data-start="'+start+'" data-length="'+length+'">'+count+'</option>';

					start = start + page_info.length;
				}

				$('#pagelist').html(html);

				$('#pagelist').val(page_info.page);
			}
		});
	}

	load_data();

	$('#pagelist').change(function(){

		var start = $('#pagelist').find(':selected').data('start');

		var length = $('#pagelist').find(':selected').data('length');

		load_data(start, length);

		var page_number = parseInt($('#pagelist').val());

		var test_table = $('#customer_table').dataTable();

		test_table.fnPageChange(page_number);

	});
	

});	
</script>


fetch.php



<?php

//fetch.php

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

$column = array("customer_id", "customer_first_name", "customer_last_name", "customer_email", "customer_gender");

$query = "SELECT * FROM customer_table ";

if(isset($_POST["search"]["value"]))
{
	$query .= '
	WHERE customer_id LIKE "%'.$_POST["search"]["value"].'%" 
	OR customer_first_name LIKE "%'.$_POST["search"]["value"].'%" 
	OR customer_last_name LIKE "%'.$_POST["search"]["value"].'%" 
	OR customer_email LIKE "%'.$_POST["search"]["value"].'%" 
	OR customer_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 customer_id DESC ';
}

$query1 = '';

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

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

$statement->execute();

$number_filter_row = $statement->rowCount();

$result = $connect->query($query . $query1);

$data = array();

foreach($result as $row)
{
	$sub_array = array();

	$sub_array[] = $row['customer_id'];

	$sub_array[] = $row['customer_first_name'];

	$sub_array[] = $row['customer_last_name'];

	$sub_array[] = $row['customer_email'];

	$sub_array[] = $row['customer_gender'];

	$data[] = $sub_array;
}

function count_all_data($connect)
{
	$query = "SELECT * FROM customer_table";

	$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);

?>







Friday, 16 April 2021

How to Export Data in Excel using Codeigniter 4


In this tutorial, you can learn How to Export Data to Excel in Codeigniter 4 using PHPSpreadsheet library. After publishing of new version of Codeigniter framework, then there is lots of changes has come in Codeigniter latest version than previous version. In latest version of Codeigniter framework, we can perform more operation by writing less code. So for this, we have to learn all things again in Codeigniter 4 framework. For this reason here we have again publish tutorial on export mysql data to excel sheet using Codeigniter 4 framework.

Exporting of Mysql data into Excel sheet in Codeigniter 4 framework by using PHPSpreadsheet library. From this post you can find the solution of how to export data in excel format using PHPSpreadsheet library with Codeigniter 4.

In most of the web application, in which we have work with dynamic data then we need to export that data from web application. So at that time we have prefer excel format for get data from web application. This is because Excel format is most of the widely used. So we need to export data from web application to excel format with Codeigniter 4 framework. So for this reason in this tutorial will help because in this post you can find step by step process for how to export dynamic mysql database data into Excel sheet using Codeigniter 4 application. In this post we will use PHPSpreadsheet library with Codeigniter 4 framework for export data into excel format or create and save dynamic data in excel file.


How to Export Data in Excel using Codeigniter 4


  1. Download & Install Codeigniter 4 framework
  2. Set Global Environment Variable value
  3. Create Mysql Table
  4. Create Database connection
  5. Download PHPSpreadsheet Library in Codeigniter 4
  6. Create Model Class
  7. Create Data Seeder Class for Fake data
  8. Create Controller Class
  9. Create View File
  10. Start Codeigniter 4 Server

1 - Download & Install Codeigniter 4 framework


For make Codeigniter 4 application, first we need to download Codeigniter 4 framework. So for download and install Codeigniter 4 framework. We have go to terminal and under this we will use Composer for download Codeigniter 4 framework. So for download Codeigniter 4 framework, we have to run following command in terminal.


composer create-project codeigniter4/appstarter excel_export


This command will first make excel_export folder under define directory and then after it will download Codeigniter 4 framework.

2 - Set Global Environment Variable value


After download Codeigniter 4 framework, so in root folder of Codeigniter 4 framework, you can find env file. So for use Global variable or environment variable, we need to first convert env file to .env file. For this things, we have open terminal and run following command.


copy env .env


After run above command it will copy env file to .env file. So now we are ready to use environment variables in Codeigniter 4 framework.

By default Codeigniter 4 starts in production mode, so it will not display error on web page. So for this first we need to define development mode, so it will display error on web page. For this open .env file and define following enivonment variable value.

.env

#--------------------------------------------------------------------
# ENVIRONMENT
#--------------------------------------------------------------------

CI_ENVIRONMENT = development


After define this environment variable value, now codeigniter 4 application is in development mode.





3 - Create Mysql Table


For work with database, so here first you have to create database in your PhpMyAdmin and after create database you have to create table in that database. So for create table, you have to run following sql script, which will create employee table in your database.


CREATE TABLE students (
    employee_id int(5) unsigned NOT NULL AUTO_INCREMENT,
    employee_name varchar(100) NOT NULL,
    employee_mobile varchar(100) NOT NULL,
    employee_email varchar(20) DEFAULT NULL,
    employee_department varchar(50) DEFAULT NULL
    PRIMARY KEY (employee_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;


4 - Create Database connection


After create table in your database, next we needt to connect database with this Codeigniter 4 application. For this we have to open .env file from Codeigniter 4 framework root. Under this file, you have to search DATABASE and then after you can see the database connection envionment variables.

.env

#--------------------------------------------------------------------
# DATABASE
#--------------------------------------------------------------------

database.default.hostname = localhost
database.default.database = testing
database.default.username = root
database.default.password = 
database.default.DBDriver = MySQLi


After set the value of this environment variable it will make mysql database connection with your Codeigniter 4 application using .env file.

5 - Download PHPSpreadsheet Library in Codeigniter 4


In Codeigniter 4 framework, for export data to excel we need to download PHPSpreadsheet library, so for download PHPSpreadsheet we will use composer. So for this we have open terminal and run following command.


composer require phpoffice/phpspreadsheet


This command will download PHPSpreadsheet library package into Codeigniter 4 framework /vendor folder.

6 - Create Model Class


In Codeigniter 4 framework, for perform database related operation, we need to create model file. So for create model file, we have need to run following spark command.


php spark make:model Employee --suffix


This command will create EmployeeModel.php file at /app/Models folder. So you need to open EmployeeModel.php file and write this following code into it.

app/Models/EmployeeModel.php

<?php

namespace App\Models;

use CodeIgniter\Model;

class EmployeeModel extends Model
{
	protected $DBGroup              = 'default';
	protected $table                = 'employee';
	protected $primaryKey           = 'employee_id';
	protected $useAutoIncrement     = true;
	protected $insertID             = 0;
	protected $returnType           = 'array';
	protected $useSoftDelete        = false;
	protected $protectFields        = true;
	protected $allowedFields        = ["employee_name", "employee_mobile", "employee_email", "employee_department"];

	// Dates
	protected $useTimestamps        = false;
	protected $dateFormat           = 'datetime';
	protected $createdField         = 'created_at';
	protected $updatedField         = 'updated_at';
	protected $deletedField         = 'deleted_at';

	// Validation
	protected $validationRules      = [];
	protected $validationMessages   = [];
	protected $skipValidation       = false;
	protected $cleanValidationRules = true;

	// Callbacks
	protected $allowCallbacks       = true;
	protected $beforeInsert         = [];
	protected $afterInsert          = [];
	protected $beforeUpdate         = [];
	protected $afterUpdate          = [];
	protected $beforeFind           = [];
	protected $afterFind            = [];
	protected $beforeDelete         = [];
	protected $afterDelete          = [];
}



7 - Create Data Seeder Class for Fake data


In this step, we have to create fake data and insert into employee table for demostrate this feature. So for generate dummy data, we need to crate seeder file and then after we will use Faker Library and this library by default available in Codeigniter 4 framework. For create seeder class file, we go to terminal and run following spark command.


php spark make:seeder Employee --suffix


This command will create EmployeeSeeder.php file into /app/Database/Seeds directory. So we have to open EmployeeSeeder.php file and write following code into this file.

app/Database/Seeds/EmployeeSeeder.php

<?php

namespace App\Database\Seeds;

use CodeIgniter\Database\Seeder;
use App\Models\EmployeeModel;
use Faker\Factory;

class EmployeeSeeder extends Seeder
{
	public function run()
	{
		$data = [];

		for($count = 0; $count < 50; $count++)
		{
			$data[] = $this->generate_data();
		}

		$employee_object = new EmployeeModel();

		$employee_object->insertBatch($data);
	}

	function generate_data()
	{
		$faker = Factory::create();

		return [
			"employee_name"		=>	$faker->name(),
			"employee_mobile"	=>	$faker->phoneNumber,
			"employee_email"	=>	$faker->email,
			"employee_department" 	=> $faker->randomElement(["Finance","Marketing","Production","Inventory"])
		];
	}
}






Once you have write above code then we need to run above seeder file for generate fake data and insert into employee table. So for run above script, we need to go terminal and run following spark command.


php spark db:seed EmployeeSeeder


8 - Create Controller Class


For handle http request, we need to create controller class file in Codeigniter 4 framework. So for create controller file, we have to run following spark command in terminal.


php spark make:controller Employee --suffix


Above command will create EmployeeController.php file at /app/Controllers directory. So we shoult open EmployeeController.php file and write following code into it.

app/Controllers/EmployeeController.php

<?php

namespace App\Controllers;

use App\Controllers\BaseController;

use App\Models\EmployeeModel;

use PhpOffice\PhpSpreadsheet\Spreadsheet;

use PhpOffice\PhpSpreadsheet\Writer\Xlsx;

class EmployeeController extends BaseController
{
	public function index()
	{
		$employee_object = new EmployeeModel();

		$data = $employee_object->findAll();

		return view("view_employee", ["data" => $data]);
	}

	function export()
	{
		$employee_object = new EmployeeModel();

		$data = $employee_object->findAll();

		$file_name = 'data.xlsx';

		$spreadsheet = new Spreadsheet();

		$sheet = $spreadsheet->getActiveSheet();

		$sheet->setCellValue('A1', 'Employee Name');

		$sheet->setCellValue('B1', 'Email Address');

		$sheet->setCellValue('C1', 'Mobile No.');

		$sheet->setCellValue('D1', 'Department');

		$count = 2;

		foreach($data as $row)
		{
			$sheet->setCellValue('A' . $count, $row['employee_name']);

			$sheet->setCellValue('B' . $count, $row['employee_email']);

			$sheet->setCellValue('C' . $count, $row['employee_mobile']);

			$sheet->setCellValue('D' . $count, $row['employee_department']);

			$count++;
		}

		$writer = new Xlsx($spreadsheet);

		$writer->save($file_name);

		header("Content-Type: application/vnd.ms-excel");

		header('Content-Disposition: attachment; filename="' . basename($file_name) . '"');

		header('Expires: 0');

		header('Cache-Control: must-revalidate');

		header('Pragma: public');

		header('Content-Length:' . filesize($file_name));

		flush();

		readfile($file_name);

		exit;
	}
}



Under this file, we have create two method under this controller class file.

index() - This is root method of this controller class. This method will fetch data from employee table and display on view file in html table format by using EmployeeModel class.

export() - This method has received request for export data into excel file. So under this method we have use PHPSpreadsheet library for export data into excel sheet and download into excel file in local computer.

9 - Create View File


For display output in browser, we need to create view file in Codeigniter 4 framework. So here we have create view_employee.php file in /app/Views folder. Under this file, we will load all employee data in html table format with excel export button.

app/Views/view_employee.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes">
    <!-- CSS only -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous">
    <title>Export Mysql Data to Excel in Codeigniter 4 using PHPSpreadsheet</title>
</head>
<body>
    <div class="container">
        <h2 class="text-center mt-4 mb-4">Export Mysql Data to Excel in Codeigniter 4 using PHPSpreadsheet</h2>
        <span id="message"></span>
        <div class="card">
            <div class="card-header">
                <div class="row">
                    <div class="col-md-6">Employee Data</div>
                    <div class="col-md-6" align="right">
                        <a href="<?php echo base_url('employeecontroller/export'); ?>" class="btn btn-success">Export</a>
                    </div>
                </div>
            </div>
            <div class="card-body">
                <div class="row justify-content-md-center">
                    <div class="table-responsive">
                        <table class="table table-bordered">
                            <tr>                                
                                <th>Employee Name</th>
                                <th>Email</th>
                                <th>Mobile</th>
                                <th>Department</th>                                
                            </tr>
                            <?php
                            foreach($data as $row)
                            {
                            ?>
                            <tr>
                                <td><?php echo $row["employee_name"];?></td>
                                <td><?php echo $row["employee_email"]; ?></td>
                                <td><?php echo $row["employee_mobile"]; ?></td>
                                <td><?php echo $row["employee_department"]; ?></td>
                            </tr>
                            <?php
                            }
                            ?>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>


10 - Start Codeigniter 4 Server


After follow all above steps, lastly we have to test this code in browser. So before test, we need to start Codeigniter 4 server. So for start development server, we need to run following spark command in terminal.


php spark serve


So this command will start server and provide us base url of our Codeigniter 4 application. So for run above script you have to hit following url in browser.


http://localhost:8080/employeecontroller


Lastly, we hope this post will really help you to learn How to Export data into Excel format with Codeigniter 4 using PHPSpreadsheet library in a step by step detailed process.

Monday, 5 April 2021

Laravel 8 Tutorial - Join Multiple Table using Eloquent Model


In this post, we have share tutorial on How to join multiple tables using Eloquent Model in Laravel framework and then after fetch data from multiple table and display on web page in HTML table format. So in this post you will find the solution of how to fetch data from multiple table by join multiple table using Eloquent Model under this Laravel framework. In this post we will use inner join for fetch data data from multiple table using Eloquent join table relationship. So by using this tutorial, you can learn How to retrieve data from multiple tables using join multiple table with eloquent model relationship in single query run under this Laravel 8 framework.

So If you want to learn How to Join Multiple Tables in Laravel framework using Eloquent Model relationship then this post will help you, because in this post you can find step by step guide for implement how can we implement inner join for multiple tables join using Eloquent model under this Laravel framework. Under this post we have use Eloquent model in place of simple Laravel join, this is because Laravel Eloquent model is more effective that simple Laravel join while we have to fetch data from multiple table in single query. So for this here we have use Eloquent model for join multiple table in Laravel framework. Below you can find step by step guide for how to join multiple table using Laravel eloquent model.


Laravel 8 Tutorial - Join Multiple Table using Eloquent Model

  • Download Laravel Framework
  • Make Database connection
  • Create Model Class
  • Create Controller Class
  • Create View Blade file
  • Set Route
  • Run Laravel Server

Download Laravel Framework


For download fresh copy of Laravel framework, so first we have to into command prompt and run following command. This command will make join_table directory and under that directory it will download Laravel framework latest version.


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


Make Database connection


After download and install Laravel framework and after this we want to make first database connection. So for make database connection, we have to open .env file and under this file, we have to define mysql database configuration. So it will create database connection in Laravel framework.


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


Once you have make database connection, then after we have to make table in mysql database. So for this you have to run following sql script in your local database, so it will create table in your define mysql database.


--
-- Table structure for table `city`
--

CREATE TABLE `city` (
  `city_id` int(11) NOT NULL,
  `state_id` int(11) NOT NULL,
  `city_name` varchar(250) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `city`
--

INSERT INTO `city` (`city_id`, `state_id`, `city_name`) VALUES
(1, 1, 'New York city'),
(2, 1, 'Buffalo'),
(3, 1, 'Albany'),
(4, 2, 'Birmingham'),
(5, 2, 'Montgomery'),
(6, 2, 'Huntsville'),
(7, 3, 'Los Angeles'),
(8, 3, 'San Francisco'),
(9, 3, 'San Diego'),
(10, 4, 'Toronto'),
(11, 4, 'Ottawa'),
(12, 5, 'Vancouver'),
(13, 5, 'Victoria'),
(14, 6, 'Sydney'),
(15, 6, 'Newcastle'),
(16, 7, 'City of Brisbane'),
(17, 7, 'Gold Coast'),
(18, 8, 'Bangalore'),
(19, 8, 'Mangalore'),
(20, 9, 'Hydrabad'),
(21, 9, 'Warangal');

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

--
-- Table structure for table `country`
--

CREATE TABLE `country` (
  `country_id` int(11) NOT NULL,
  `country_name` varchar(250) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `country`
--

INSERT INTO `country` (`country_id`, `country_name`) VALUES
(1, 'USA'),
(2, 'Canada'),
(3, 'Australia'),
(4, 'India');

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

--
-- Table structure for table `state`
--

CREATE TABLE `state` (
  `state_id` int(11) NOT NULL,
  `country_id` int(11) NOT NULL,
  `state_name` varchar(250) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `state`
--

INSERT INTO `state` (`state_id`, `country_id`, `state_name`) VALUES
(1, 1, 'New York'),
(2, 1, 'Alabama'),
(3, 1, 'California'),
(4, 2, 'Ontario'),
(5, 2, 'British Columbia'),
(6, 3, 'New South Wales'),
(7, 3, 'Queensland'),
(8, 4, 'Karnataka'),
(9, 4, 'Telangana');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `city`
--
ALTER TABLE `city`
  ADD PRIMARY KEY (`city_id`);

--
-- Indexes for table `country`
--
ALTER TABLE `country`
  ADD PRIMARY KEY (`country_id`);

--
-- Indexes for table `state`
--
ALTER TABLE `state`
  ADD PRIMARY KEY (`state_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `city`
--
ALTER TABLE `city`
  MODIFY `city_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=22;

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

--
-- AUTO_INCREMENT for table `state`
--
ALTER TABLE `state`
  MODIFY `state_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10;





Create Model Class


In Laravel framework, we have to create model class for database related operation. So for create model classe using compost, we have go to command prompt and run following command, this command will make model class file with name Country.php under app/Models folder.


php artisan make:model Country


After create model class, we have to open that file and under that file we have to define mysql table name details and column details.


<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Country extends Model
{
    use HasFactory;

    protected $table = 'country';

    protected $fillable = [
    	'country_name'
    ];
}



Create Controller Class


Under this Laravel framework, for handle HTTP request we have to create controller class. So for create controller using compost, we have go to command prompt and run following command.


php artisan make:controller JointableController


Once your controller class has been create then for open that file, we have go to app/Http/Controllers/JointableController.php file and under this file you have write following code for join multiple table using eloquent model and fetch data from multiple table in single query execution.


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\Country;

class JointableController extends Controller
{
    function index()
    {
    	$data = Country::join('state', 'state.country_id', '=', 'country.country_id')
              		->join('city', 'city.state_id', '=', 'state.state_id')
              		->get(['country.country_name', 'state.state_name', 'city.city_name']);

       	/*Above code will produce following query

        Select 
        	`country`.`country_name`, 
        	`state`.`state_name`, 
        	`city`.`city_name` 
        from `country` 
        inner join `state` 
        	on `state`.`country_id` = `country`.`country_id` 
        inner join `city` 
        	on `city`.`state_id` = `state`.`state_id`

        */

        return view('join_table', compact('data'));
    }
}

?>


Create View Blade file


For display HTML output in browser, so we have to create view blade file in Laravel framework. In Laravel framework view blade file has been store under resources/views folder. Under this file, we have create join_table.blade.php file. Under this file, it will received data from controller class file. You can find source code of this view blade file in below.


<html>
    <head>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>How to Join Table in Laravel 8 using Eloquent Model</title>
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
    </head>
    <body>
        <div class="container">    
            <br />
            <h1 class="text-center text-primary">How to Join Multiple Table in Laravel 8 using Eloquent Model</h1>
            <br />
            <div class="table-responsive">
                <table class="table table-bordered table-striped">
                    <thead>
                        <tr>
                            <th>Country</th>
                            <th>State</th>
                            <th>City</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach($data as $row)
                            <tr>
                                <td>{{ $row->country_name }}</td>
                                <td>{{ $row->state_name }}</td>
                                <td>{{ $row->city_name }}</td>
                            </tr>
                        @endforeach
                    </tbody>
                </table>
            </div>
        </div>
    </body>
</html>


Set Route


Under this Laravel framework, we have to set route of the controller method. For set route in Laravel 8 framework, we have to open routes/web.php file. In Laravel 8 framework for set route, we have to first import our controller class under this web.php file. And for set route you can find source code below.


<?php

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\JointableController;

Route::get('/', function () {
    return view('welcome');
});

Route::get('join_table', [JointableController::class, 'index']);



Run Laravel Server


After follow all above steps now all are set now we want to run Laravel application in browser. So for this, we have to go command prompt and run following command.


php artisan serve


Once you have run above command so after run this command it will provide us base url of our Laravel application. So for check above script output, we have to hit following url in browser.


http://127.0.0.1/join_table


Sunday, 4 April 2021

Everything you need to know about WordPress Plugin Development, Tools and Setup


You may have heard the names like Yoast SEO, Jetpack, Elementor etc. These are called plugins in terms of WordPress language. With the quick-creating industry, we should attempt to adapt up to the cutting edge innovations to pro in the race.

Plugins are extended highlights to build the usefulness of your site. There are numerous(almost 60000) plugins accessible free at WordPress.com.

All the plugins are worked to a specific need of the site. In any case, now and again there emerges an extraordinary necessity to make a site useful.

In such cases, a plugin should be modified likewise. There are different approaches to modify a plugin. WordPress Plugin improvement devices are one of them.

The initial step is to gauge the cost of WordPress plugin development. By embracing certain ways you will get an exact assessment to manufacture your customized plugin.

Building up a tweaked plugin is a perplexing system anyway utilizing the right instruments that suits your involved to work will without a doubt help. These devices have a negligible and simple expectation to learn and adapt that any novice designer can embrace.

Allow us to talk about a portion of the significant tools that will help you towards your plugin development.

WordPress Plugin Development Tools


1. Notepad ++


At any point, can you build up your plugin in Notepad? Presently even a non-engineer can fabricate a profoundly utilitarian plugin.

Notepad is supported by Notepad++ Download Manager. The absolute initially drawing-in mark of this device is it is totally liberated from cost! Obviously, we realize that right. It is authorized by GNU and a free source upheld by OS windows.

It is coded in C++ and utilizes Win 32 API and STL which are relatively more modest projects with high running speed.

An XML file will contain the list of plugins that gets downloaded with the help of the Plugin manager.

2. Atom


This has obtained its name as the 'hackable editor of 21st Century. Any designer can get to Atom and add to its code. It is an open-source stage at GitHub. It empowers cross-stage altering where you can deal with OS X, Windows, or Linux.

It even fuses an auto-fulfillment include which will assist you with coding quicker and effectively.

It can contrast your codes with numerous sheets and even empowers you to alter across the records.

3. Brackets


This is a live-altering editorial manager which assists you with citing the progressions in the running program while altering. It is created by Adobe.

Likewise, it contains a dedicatedwiki that will give you the wellspring of data at whatever point you are stuck in the midst of the codes. It similarly offers help to deliver SCSS or LESS records.



4. PHPUnit


It is especially appropriate for WordPress as its code is written in PHP. It is a trying instrument that will test your code structure before at last getting into plugin coding.

You need to ensure if the plugin supervisor is without a bug. Continuously attempt to check the device prior to using it on the fundamental site.

Starting there, you'll presumably have to investigate the bounty of documentation to get comfortable with all you'll need to consider the apparatus.

5. Travis CI


Travis CI is a reciprocal apparatus for PHPUnit that naturally runs your tests as you submit changes to GitHub. It's wide open-source projects and will assist you with guaranteeing your code won't break under different worker conditions.

The tool deals with the premise of Continuous Integration (CI), basically, little code combines executed oftentimes, instead of unpredictable clearing submits. The testing cycle will clone your GitHub vault in a virtual worker, do a few forms and tests, and on the off chance that the code passes, will convey it to your worker.

6. WordPress Plugin Boilerplate


WordPress Plugin boilerplate is the coordinated, generally normalized, and object-oriented instrument. Being open-source, it has numerous commitments around the world. It adheres to both coding norms and documentation guidelines, so you need not quest for it without fail.

7. hookr.io


Hooks are at the establishment of WordPress advancement. Basically, Hooks are code that empower you to utilize capacities incorporated into WordPress' center. That way, you can develop the establishment WordPress offers, without making changes to the center programming.

Most plugins depend vigorously on hook, and hookr.io contains a list of the relative multitude of choices available to you. Furthermore, there's a hookr.io module that empowers you to review every one of the snares your current plugins use, so you can take apart how they work.

What will you need to get started?


1. A text editor


This is where you will write your code. The best text editors are notepad++, sublime, atom etc.

2. An FTP client


FileZilla is the best FTP client to transfer your files.

3. A WordPress Website


Website is the core where you are going to connect your plugins. Website setup is needed to test and alter your codes in order to see the changes.

There are three steps to Develop a WordPress Plugin


1. Access your site to FTP



To get started you need to access your website via FTP only if your host provides it. You can use FileZilla for it. You will need to enter the credentials as provided by your host. Finally, click Quickconnect.

2. Setup a folder for your plugin



As every WordPress plugin development encounters its own folder, you need to set up a folder for your customized plugin. Create a folder in the WordPress directory.

3. Setup your custom plugin’s base file



Clicking the folder will redirect you to the text editor. Write your code in the editor and keep adding it. You will get to see the editing live in your dashboard.

Many customize plugins like wooCommerce pdf vouchers and social auto poster use the tool Atom. The text editor they use is sublime. Many of the great plugins are even created in Notepad. Imagine the skill Plugin developers ingrain.

Conclusion


You can now customize your plugin and contribute to WordPress. It will boost your website performance. In this competitive world making the best plugin will be your sword.

Connect to any WordPress plugin developer and get your customized plugin. Plugin development is an important process enhancing your skills. Once you commence your codes, you will definitely create a heap of plugins.

Saturday, 3 April 2021

Laravel vs Codeigniter, Which is Better PHP Framework?

Laravel vs Codeigniter, Which is Better PHP Framework?

With time, the PHP framework has turned into the most preferred choice when talking about developing web applications for a company. Although there are numerous PHP frameworks which are available in the market, demand for Laravel and CodeIgniter is increasing rapidly.

Laravel


Laravel is an open-source framework that is based on PHP programming. The platform was intended for the development of web applications by using MVC architectural patterns. It is basically evolved to alleviate the development task for the developers since it can take care of the general tasks.

The general tasks in web projects include web page sessions, caching, routing, and authentication. Hiring dedicated Laravel developers can solve much of your problems. Laravel has refined, yet expressive syntax.

The following are some attractive features of Laravel:

  • Contains in-built modules and libraries
  • Define numerous routes
  • Availability of different test cases
  • Query Builder and ORM
  • Configuration management features
  • Lightweight template engine
  • Schema builder

CodeIgniter


CodeIgniter is a powerful Application Development Framework for developers to create websites with the help of the PHP framework. Its toolkit, such as a rich set of libraries, helps in developing full-featured online applications in less time because there is no need to write the code from scratch. You can create dynamic websites through CodeIgniter. Moreover, the users get full liberty since they are not required to use the MVC development pattern.

The following are some interesting features of CodeIgniter:

  • Security and XSS Filtering
  • Extremely compact
  • Model-View-Controller Based System
  • Query Builder Database Support
  • Session Management
  • Form and Data Validation
  • Supports the email attachments


Comparison between Laravel and Codeigniter


Being popular PHP framework options in the market, it is difficult to decide on one. So, the below-mentioned aspects can help in making the decision:

More compatible with upgraded PHP version: Currently, the advanced version PHP 7 is available in the market for developers. Indeed, both frameworks Laravel and CodeIgniter support PHP 7.X versions. However, there are some issues faced by coders and testers of CodeIgniter during the development as well as testing of a project. Thus, Laravel has the upper hand when it comes to compatibility.

Technical Documentation: The CodeIgniter framework cannot be beaten by any other framework in terms of the fully organized and simple to understand documentation. The notions used in building and designing a website through the CodeIgniter framework are pretty much easy to understand since they are certainly illustrated in the file in a comprehensive way. However, the Laravel framework includes difficult-to-understand documentation. So, CodeIgniter is more useful.

Usage of Libraries: Laravel incorporates object-oriented libraries, which play a vital role during the development of an effective website. Autocomplete features can support its libraries to carry out the development process easily. Whereas CodeIgniter libraries do not have such features, and they do not contribute to convenient development. Therefore, Laravel makes the development process easy.

Stability and Reliability: Both PHP frameworks, i.e., Laravel and CodeIgniter are stable and reliable. While the chances of bugs and other technical problems are not much in CodeIgniter, Laravel has higher chances of such issues.

Community Preference: Developers use Laravel and CodeIgniter framework to work on all types of website projects, be it small scale or large scale. However, the development community of the Laravel framework is larger as compared to CodeIgniter.

Modular packages: Laravel assists web programmers to split up the task into short module packages. However, the CodeIgniter framework demands developers use a modular extension to keep modules up. So, the latter framework does not provide modular code separation by default.

Simplified Database: The Laravel framework has a feature of skeptic relocations so that it can share the database without using complicated coding. But, the CodeIgniter framework does not come up with a highlight for the relocation of database patterns.

In-built Template Engine: There is an inbuilt template engine in the Laravel framework, namely blade to optimize the web performance. However, the CodeIgniter framework does not have a built-in template engine. The programmers are needed to integrate the CodeIgniter framework with a template engine tool such as Smarty to enhance the web performance. Thus, the former framework provides more convenience.

Compatibility with HTTPS: To transmit the information securely, HTTPS protocol plays an essential role. Laravel has considerable security since it supports HTTPS routes whereas, in the case of the CodeIgniter framework, it is not fully compatible with HTTPS.

REST Application Programming Interface: Laravel framework includes RESTful controllers to create various REST application programming interfaces without putting in extra time or effort. However, in the case of the CodeIgniter framework, there is a requirement for additional code to build the REST API.

Object-Relation Mapping: Laravel framework uses eloquent as object relation, whereas CodeIgniter framework uses an advanced version of a database design known as an active record to regulate database operations by writing small code.

Routing: Developers get the routing options in both Laravel and CodeIgniter frameworks. CodeIgniter provides implicit as well as explicit routing. Whereas, Laravel is more reliable and flexible when sending routing requests. Thus, developers can get more benefits from Laravel as compared to CodeIgniter.

Authentication Feature: In the Laravel framework, the authentication class assists developers in implementing authorization and authentication. However, the developers require to write custom CodeIgniter extensions for making use of authentication and authorize features.

Security: When it comes to any kind of web application, security is a prominent aspect. Laravel has features of better authorization and authentication checks. Laravel framework is a comparatively more secure framework than CodeIgniter.

Both frameworks are the prominent PHP frameworks to develop web applications. Although Laravel is comparatively slightly difficult for the developers to learn, its additional features make it suitable for a versatile website. On the contrary, CodeIgniter is convenient to use and a better option for small projects that do not require additional features.

Author Bio :

Harikrishna Kundariya, a marketer, developer, IoT, ChatBot & Blockchain savvy, designer, co-founder, Director of eSparkBiz Technologies. His 8+ experience enables him to provide digital solutions to new start-ups based on IoT and ChatBot.