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


Wednesday, 31 March 2021

Toast Notification for Check Internet Connection with Bootstrap 4 & javascript


In this post, you will learn how to make a Toast Notification for Detect Internet Connection status using javascript, HTML and Bootstrap 4 Toast component. In this tutorial, we will use javascript and Bootstrap 4 library for display internet connection status. In web development display of push notification regarding Internet connection status feature is very useful, because in this middle of surfing website and suddenly internet connection lost, then at that time this push toast notification is very effective for display of internet connection status on web page.

Under this Toast Notification for check Internet connection status post, and under this we page, we will write light weight javascript code with Bootstrap 4 Toast component. So based on Internet connection status like online or offline then it will change its icon, text color and text according to status of internet connection. Here we have use Bootstrap 4 Toast component, so this component has some build in animation, so when internet connection status changes then it will display push toast notification at right side top of the web page, so user can see internet connection has lost or not.

For build this detection of Internet connection under this post, we have use simple javascript navigator.onLine code, This code has return true if internet connection is online and if it return false that means internet connection is offline. So based on this value toast notification icon, text and color will be change and it will display pust toast notification on web page. This push notification will display on web page, when internet connection status will be change. For implement this feature in your web application, you have to copy below code in your web based application and you can implement this how to display internet connection status on web page by using push notification which has been build with javascript and Bootstrap 4 Toast component.

Toast Notification for Check Internet Connection with Bootstrap 4 & javascript





Source Code






<!DOCTYPE html>
<html>
  	<head>
    	<title>Toast Notification for Check Internet Connection with Bootstrap 4 & javascript</title>
    	<meta name="viewport" content="width=device-width, initial-scale=1.0">
      	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
  		<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  		<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
  		<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
  		<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.4.1/font/bootstrap-icons.css">
  	</head>
  	<body>
  		<div class="container">
  			<br />
  			<br />
    		<h1 align="center">Toast Notification for Check Internet Connection with Bootstrap 4 & javascript</h1>
    		<br />    		
    	</div>
    	
  	</body>
</html>

<div class="toast" style="position: absolute; top: 25px; right: 25px;">
    <div class="toast-header">
        <i class="bi bi-wifi"></i>&nbsp;&nbsp;&nbsp;
        <strong class="mr-auto"><span class="text-success">You're online now</span></strong>
        <button type="button" class="ml-2 mb-1 close" data-dismiss="toast" aria-label="Close">
            <span aria-hidden="true">&times;</span>
        </button>
    </div>
    <div class="toast-body">
        Hurray! Internet is connected.
    </div>
</div>

<script>

var status = 'online';
var current_status = 'online';

function check_internet_connection()
{
    if(navigator.onLine)
    {
        status = 'online';
    }
    else
    {
        status = 'offline';
    }

    if(current_status != status)
    {
        if(status == 'online')
        {
            $('i.bi').addClass('bi-wifi');
            $('i.bi').removeClass('bi-wifi-off');
            $('.mr-auto').html("<span class='text-success'>You are online now</span>");
            $('.toast-body').text('Hurray! Internet is connected.');
        }
        else
        {
            $('i.bi').addClass('bi-wifi-off');
            $('i.bi').removeClass('bi-wifi');
            $('.mr-auto').html("<span class='text-danger'>You are offline now</span>");
            $('.toast-body').text('Opps! Internet is disconnected.')
        }

        current_status = status;

        $('.toast').toast({
            autohide:false
        });

        $('.toast').toast('show');
    }
}

check_internet_connection();

setInterval(function(){
    check_internet_connection();
}, 1000);

</script>

Thursday, 11 March 2021

Dynamic Dependent Dropdown using Ajax in Codeigniter 4



This is Codeigniter 4 tutorial on Dynamic dependent dropdown using Ajax. This is furthermost tutorial on Dynamic dependent select box in Codeigniter 4 with Ajax jQuery. Dynamically dependent select box is mainly used in the country state and city selection or category and sub category option selection, we have used on the web page. And under this dynamic dependent dropdown list box child field data changes according to the value of it's parent field.

For make dynamic dependent select box or dropdown, we have to use Ajax jQuery with Codeigniter 4 framework. So in this post, we have make dynamic dependent select box in Codeigniter 4 using Ajax jQuery. Here you can find step by step guide for build how to create dynamic dependent select box in Codeigniter 4 using Ajax with jQuery, Mysql and Bootstrap 4 library.


Dynamic Dependent Dropdown using Ajax in Codeigniter 4


Codeigniter 4 Dynamic Dependent dropdown with Ajax


  1. Download Codeigniter 4 framework
  2. Create Table in Mysql Database
  3. Setup Mysql Database Connection
  4. Create Model File
  5. Create Controller
  6. Create View File
  7. Start Codeigniter 4 Server

Step 1 - Download Codeigniter 4 framework


In this step, you have to download the latest version of Codeigniter 4 framework. Here we will use composer for download Codeigniter 4 framework. So for this, we have to go command prompt, and then after go to directory in which you want to download and install codeigniter 4 framework and here we want to run following command.


composer create-project codeigniter4/appstarter dynamic-dependent


This command will make dynamic-dependent directory and under that directory it will download and install Codeigniter 4 framework.

Step 2 - Create Table in Mysql Database


In this step, we need to make database with name testing. So, we have to open PHPMyAdmin and under this we have to create database with name testing. And after successfully create database, we have to run following sql script for creating required table in database.


--
-- Database: `country_state_city`
--

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

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

--
-- Indexes for dumped tables
--

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

--
-- AUTO_INCREMENT for dumped tables
--

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

--
-- 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 `state`
--
ALTER TABLE `state`
  ADD PRIMARY KEY (`state_id`);

--
-- AUTO_INCREMENT for dumped tables
--

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

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

--
-- Indexes for dumped tables
--

--
-- Indexes for table `city`
--
ALTER TABLE `city`
  ADD PRIMARY KEY (`city_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;





Step 3 - Setup Mysql Database Connection


In third step, we have need to connect our Codeigniter 4 application with Mysql database. For this, we have to open app/Config/Database.php file in your text editor. And After opening of that file in texteditor, we have to define database configuration details, which we can seen below.


public $default = [
		'DSN'      => '',
		'hostname' => 'localhost',
		'username' => 'root',
		'password' => '',
		'database' => 'testing',
		'DBDriver' => 'MySQLi',
		'DBPrefix' => '',
		'pConnect' => false,
		'DBDebug'  => (ENVIRONMENT !== 'production'),
		'cacheOn'  => false,
		'cacheDir' => '',
		'charset'  => 'utf8',
		'DBCollat' => 'utf8_general_ci',
		'swapPre'  => '',
		'encrypt'  => false,
		'compress' => false,
		'strictOn' => false,
		'failover' => [],
		'port'     => 3306,
	];





Step 4 - Create Model File


After making mysql database connection, next we have to go to app/Models folder and under this we have to create three model class file for each Country, State and city table which you can find below.

app/Models/CountryModel.php

<?php

//CountryModel.php

namespace App\Models;

use CodeIgniter\Model;

class CountryModel extends Model{

	protected $table = 'country';

	protected $primaryKey = 'country_id';

	protected $allowedFields = ['country_name'];

}	

?>


app/Models/StateModel.php

<?php

//StateModel.php

namespace App\Models;

use CodeIgniter\Model;

class StateModel extends Model{

	protected $table = 'state';

	protected $primaryKey = 'state_id';

	protected $allowedFields = ['country_id', 'state_name'];

}	

?>


app/Models/CityModel.php

<?php

//CityModel.php

namespace App\Models;

use CodeIgniter\Model;

class CityModel extends Model{

	protected $table = 'city';

	protected $primaryKey = 'city_id';

	protected $allowedFields = ['state_id', 'city_name'];

}

?>





Under this all file, we have to define Mysql table name, table primary key and field name details in all model for database related operation using Model class.

Step 5 - Create Controller


In this steps, we have to create controller class for handle http request. So for create Controllers class, we have to visit app/Controllers folder and create controller with name Dynamic_dependent.php. Under this controller class, we have need to add following method under this controller class.

app/Controllers/Dynamic_dependent.php

<?php

//Dynamic_dependent.php

namespace App\Controllers;

use App\Models\CountryModel;

use App\Models\StateModel;

use App\Models\CityModel;

class Dynamic_dependent extends BaseController
{
	function index()
	{
		$countryModel = new CountryModel();

		$data['country'] = $countryModel->orderBy('country_name', 'ASC')->findAll();

		return view('dynamic_dependent', $data);
	}

	function action()
	{
		if($this->request->getVar('action'))
		{
			$action = $this->request->getVar('action');

			if($action == 'get_state')
			{
				$stateModel = new StateModel();

				$statedata = $stateModel->where('country_id', $this->request->getVar('country_id'))->findAll();

				echo json_encode($statedata);
			}

			if($action == 'get_city')
			{
				$cityModel = new CityModel();
				$citydata = $cityModel->where('state_id', $this->request->getVar('state_id'))->findAll();

				echo json_encode($citydata);
			}
		}
	}
}

?>


Step 6 - Create View File


Under this step, we have to create view files with name dynamic_dependent.php under Views directory. This file will used for display html output in browser.


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes">
    <link rel="stylesheet" href="<?php echo base_url('/css/bootstrap.min.css'); ?>" >
    <script src="<?php echo base_url('/js/jquery.min.js'); ?>"></script>
    <script src="<?php echo base_url('/js/popper.min.js'); ?>"></script>
    <script src="<?php echo base_url('/js/bootstrap.min.js'); ?>"></script>
    <title>Codeigniter 4 Dynamic Dependent Dropdown with Ajax</title>
</head>
<body>
    <div class="container">
        <h2 class="text-center mt-4 mb-4">Codeigniter 4 Dynamic Dependent Dropdown with Ajax</h2>
        <span id="message"></span>
        <div class="card">
            <div class="card-header">Codeigniter 4 Dynamic Dependent Dropdown with Ajax</div>
            <div class="card-body">
                <div class="row justify-content-md-center">
                    <div class="col col-lg-6">
                        <div class="form-group">
                            <select name="country" id="country" class="form-control input-lg">
                                <option value="">Select Country</option>
                                <?php
                                foreach($country as $row)
                                {
                                    echo '<option value="'.$row["country_id"].'">'.$row["country_name"].'</option>';
                                }
                                ?>
                            </select>
                        </div>
                        <div class="form-group">
                            <select name="state" id="state" class="form-control input-lg">
                                <option value="">Select State</option>
                            </select>
                        </div>
                        <div class="form-group">
                            <select name="city" id="city" class="form-control input-lg">
                                <option value="">Select City</option>
                            </select>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
 
</body>
</html>

<script>

$(document).ready(function(){

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

        var country_id = $('#country').val();

        var action = 'get_state';

        if(country_id != '')
        {
            $.ajax({
                url:"<?php echo base_url('/dynamic_dependent/action'); ?>",
                method:"POST",
                data:{country_id:country_id, action:action},
                dataType:"JSON",
                success:function(data)
                {
                    var html = '<option value="">Select State</option>';

                    for(var count = 0; count < data.length; count++)
                    {

                        html += '<option value="'+data[count].state_id+'">'+data[count].state_name+'</option>';

                    }

                    $('#state').html(html);
                }
            });
        }
        else
        {
            $('#state').val('');
        }
        $('#city').val('');
    });

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

        var state_id = $('#state').val();

        var action = 'get_city';

        if(state_id != '')
        {
            $.ajax({
                url:"<?php echo base_url('/dynamic_dependent/action'); ?>",
                method:"POST",
                data:{state_id:state_id, action:action},
                dataType:"JSON",
                success:function(data)
                {
                    var html = '<option value="">Select City</option>';

                    for(var count = 0; count < data.length; count++)
                    {
                        html += '<option value="'+data[count].city_id+'">'+data[count].city_name+'</option>';
                    }

                    $('#city').html(html);
                }
            });
        }
        else
        {
            $('#city').val('');
        }

    });

});

</script>


Step 7 - Start Codeigniter 4 Server


Now we have come on the last step, after follow all above step, now we need to start Codeigniter 4 framework server, so we have to command prompt and go into directory in which we have download and install Codeigniter framework, and then after we have to run following command.


php spark serve


This command will start Codeigniter 4 server and it will give us base url of our Codeigniter 4 application and for run above code, we have hit following url in browser.


http://localhost:8080/dynamic_dependent


Lastly, Under this post, we have make Codeigniter 4 Ajax dynamic dependent dropdown box. So after you have to follow above step you can successfully create Dynamic dependent dropdown in Codeigniter 4 with Ajax jQuery.

Saturday, 6 March 2021

How to Implement Fullcalendar in Laravel 8 using Ajax


In this blog, we have share with you Fullcalendar working example with Laravel 8 application. That means in this post you can find how to implement JavaScript Fullcalendar plugin in Laravel 8 framework. So by using FullCalendar, we can display our daily events or tasks and we can also schedule our event or task by using FullCalendar plugin.


Under this Laravel 8 tutorial with FullCalendar using Ajax. So in this tutorial, you can learn how to use fullcalendar in Laravel 8 application with Ajax so you can perform all operation on single page without refresh of web page. So in this tutorial you can learn how to create, edit or update and delete events in Laravel 8 framework with Fullcalendar using ajax.

This post will give you complete guide on how to integrate fullcalendar with Ajax in Laravel application. For this things you have to follow below steps.

Tutorial on FullCalendar Integration in Laravel 8


  1. Download Laravel Framework
  2. Mysql Database Connection
  3. Create Migration & Model File
  4. Create Controller Class
  5. Create Blade View File
  6. Add Routes for Controller Method
  7. Run Laravel Application


Step 1 : Download Laravel Framework


First of all, we want to download and install Laravel 8 application, so for this open terminal and run the following command in terminal for download and install Laravel 8 framework.


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


Step 2: Mysql Database Connection


In second step we want to make database connection with Laravel application, so we have to open .env file and define database configuration details for connect Laravel application with database.

.env

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


Step 3 : Create Migration & Model File


In this step, we want to create migration file for create table in our database and then after we want to create Model class file for perform database related operation.

First for create migration file, we have to run following command in terminal for created migration file.


php artisan make:migration create_events_table


This command will create one migration file under database/migrations directory. So we have to open that file and define table column defination for create table in database.

database/migrations/2021_03_05_051820_create_events_table.php

<?php

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

class CreateEventsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('events', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->dateTime('start');
            $table->dateTime('end');
            $table->timestamps();
        });
    }

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


Next, we have to create Event.php model class file under app/Models folder and under that file we have to define table column name which you can find below.

app/Models/Event.php

<?php

namespace App\Models;

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

class Event extends Model
{
	use HasFactory;

	protected $fillable = [
		'title', 'start', 'end'
	];
}

?>


After this, we want to run following command in terminal and after successfully run below command it will creates events table into database.


php artisan migrate





Step 4 : Create Controller Class


Under this step, we want to create Controller class, so for this we want to run following command in command prompt for create a controller name FullCalendarController.php file.


php artisan make:controller FullCalenderController


After successfully run above command, it will create FullCalendarController.php controller class file in app/Http/Controllers folder, so we have to open that file.

app/Http/Controllers/FullCalendarController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\Event;

class FullCalenderController extends Controller
{
    public function index(Request $request)
    {
    	if($request->ajax())
    	{
    		$data = Event::whereDate('start', '>=', $request->start)
                       ->whereDate('end',   '<=', $request->end)
                       ->get(['id', 'title', 'start', 'end']);
            return response()->json($data);
    	}
    	return view('full-calender');
    }

    public function action(Request $request)
    {
    	if($request->ajax())
    	{
    		if($request->type == 'add')
    		{
    			$event = Event::create([
    				'title'		=>	$request->title,
    				'start'		=>	$request->start,
    				'end'		=>	$request->end
    			]);

    			return response()->json($event);
    		}

    		if($request->type == 'update')
    		{
    			$event = Event::find($request->id)->update([
    				'title'		=>	$request->title,
    				'start'		=>	$request->start,
    				'end'		=>	$request->end
    			]);

    			return response()->json($event);
    		}

    		if($request->type == 'delete')
    		{
    			$event = Event::find($request->id)->delete();

    			return response()->json($event);
    		}
    	}
    }
}
?>


Under this file, first we want to import Event model class for database related operation. Under this file we have to make following two method.

index(Request $request) : This is root method of this class. This method will load full-calender.blade.php file in browser, and this method will also received ajax request for fetch event data from database and send to ajax request in json format.

action(Request $request) : This another method under this controller class. This method has mainly received ajax request for create event, update existing event details and remove event from database.




Step 5 : Create Blade View File


Under this step, we have to go into resources/views folder and then after we have to create new blade file with named full-calender.blade.php and under this file we have to add following code. Under this code you can also find JavaScript code for load event, create event, update event and delete event code with ajax request.

resources/views/full-calender.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>How to Use Fullcalendar in Laravel 8</title>
    
    <meta name="csrf-token" content="{{ csrf_token() }}" />

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.9.0/fullcalendar.css" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.9.0/fullcalendar.js"></script>
</head>
<body>
  
<div class="container">
    <br />
    <h1 class="text-center text-primary"><u>How to Use Fullcalendar in Laravel 8</u></h1>
    <br />

    <div id="calendar"></div>

</div>
   
<script>

$(document).ready(function () {

    $.ajaxSetup({
        headers:{
            'X-CSRF-TOKEN' : $('meta[name="csrf-token"]').attr('content')
        }
    });

    var calendar = $('#calendar').fullCalendar({
        editable:true,
        header:{
            left:'prev,next today',
            center:'title',
            right:'month,agendaWeek,agendaDay'
        },
        events:'/full-calender',
        selectable:true,
        selectHelper: true,
        select:function(start, end, allDay)
        {
            var title = prompt('Event Title:');

            if(title)
            {
                var start = $.fullCalendar.formatDate(start, 'Y-MM-DD HH:mm:ss');

                var end = $.fullCalendar.formatDate(end, 'Y-MM-DD HH:mm:ss');

                $.ajax({
                    url:"/full-calender/action",
                    type:"POST",
                    data:{
                        title: title,
                        start: start,
                        end: end,
                        type: 'add'
                    },
                    success:function(data)
                    {
                        calendar.fullCalendar('refetchEvents');
                        alert("Event Created Successfully");
                    }
                })
            }
        },
        editable:true,
        eventResize: function(event, delta)
        {
            var start = $.fullCalendar.formatDate(event.start, 'Y-MM-DD HH:mm:ss');
            var end = $.fullCalendar.formatDate(event.end, 'Y-MM-DD HH:mm:ss');
            var title = event.title;
            var id = event.id;
            $.ajax({
                url:"/full-calender/action",
                type:"POST",
                data:{
                    title: title,
                    start: start,
                    end: end,
                    id: id,
                    type: 'update'
                },
                success:function(response)
                {
                    calendar.fullCalendar('refetchEvents');
                    alert("Event Updated Successfully");
                }
            })
        },
        eventDrop: function(event, delta)
        {
            var start = $.fullCalendar.formatDate(event.start, 'Y-MM-DD HH:mm:ss');
            var end = $.fullCalendar.formatDate(event.end, 'Y-MM-DD HH:mm:ss');
            var title = event.title;
            var id = event.id;
            $.ajax({
                url:"/full-calender/action",
                type:"POST",
                data:{
                    title: title,
                    start: start,
                    end: end,
                    id: id,
                    type: 'update'
                },
                success:function(response)
                {
                    calendar.fullCalendar('refetchEvents');
                    alert("Event Updated Successfully");
                }
            })
        },

        eventClick:function(event)
        {
            if(confirm("Are you sure you want to remove it?"))
            {
                var id = event.id;
                $.ajax({
                    url:"/full-calender/action",
                    type:"POST",
                    data:{
                        id:id,
                        type:"delete"
                    },
                    success:function(response)
                    {
                        calendar.fullCalendar('refetchEvents');
                        alert("Event Deleted Successfully");
                    }
                })
            }
        }
    });

});
  
</script>
  
</body>
</html>


Step 6 : Add Routes for Controller Method


Under this step, we have to create route for index() and action() method of FullCalenderController.php controller class. For add routes under Laravel 8 framework, we have to open routes/web.php file and then after add the following routes into it, which you can find below.

routes/web.php

<?php

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\FullCalenderController;

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

Route::get('full-calender', [FullCalenderController::class, 'index']);

Route::post('full-calender/action', [FullCalenderController::class, 'action']);

?>


Step 7 : Run Laravel Application


In last steps, we have to run following command in terminal for start Laravel development server.


 php artisan serve


After run above command, we want to check output in browser, so for this we have to hit following url in browser.


http://127.0.0.1:8000/full-calender


Lastly, This is Laravel 8 fullcalendar tutorial, and here you can successfully learn how can we integrate fullcalendar in Laravel 8 framework with Ajax and as well as here we have load, create, edit and remove events from fullcalendar using Ajax in Laravel 8 application.





Thursday, 4 March 2021

Best PHP Blog Scripts and Blogging Platforms

Best PHP Blog Scripts and Blogging Platforms


Blogs have started to be one of the best ways of marketing, this helps the business express their views and inform the users about their products and services from a detailed point of view. Several technological advances are striving to take the shine out of blogging but it still remains intact and is accepted by most people.

Many businesses are now realizing the importance of blogging and are applying the same strategy to bring about the best changes to their marketing strategy. Be it the food business or electronics product, each field has seen a huge rise in the development of technology.

The adoption of such a technology in the daily use of business is made easy using PHP, people have been using a food delivery PHP script and others quite frequently. Now, businesses are turning towards using PHP blog scripts. The scripts come with robust technology to convert visitors to customers and also involve a content management system inside the script.

Let us see here some blogging scripts that you can readily use for the business.

Best PHP blog scripts


1. Varient News Magazine Script


The varient news magazine is a script based on PHP, it consists of all the features of a newsletter blogging platform where the script runs on dynamic news and blogs. The script is segmented into several parts like sports, political, lifestyle, and others. The script is very user-friendly and has an impressive user experience. The script jas different panels that can be managed by several authors.




2. Blog Manager Module for CMS pro


The Blog manager module has a very immersive script and interface and is among one of the best and most popular blog scripts. The system is comprehensive and is made up of five plugins associated with it like search, menu, archive, popular, latest.

The layouts of the platform are unique and do not have multiple formats. It also has rating sections that can be used for feedback from the real world.

3. Infinite Blog and Magazine Script


Infinite is a very clean PHP blog script, it has different interfaces associated with it, this provides a relatively responsive and user-friendly interface. The business can manage its custom pages, categories, user comments, advanced settings, and contact messages, with the help of panels associated with them.

The script is secured and is used for SEO optimization and is fast and easy to use. The system has an ad management system Incorporated.

4. Active newspaper CMS


The active newspaper helps to stand out in the market with its immersive UX and UI interface. The script has a powerful panel that can be used to manage reporters and bloggers, video uploads, and polls and so much more. The log-in credentials in the system are connected with the social network and have a different system in its inclusion.

The system has monetization of the blog, ads, homepage, gallery, and more. All the features of well-established and professional magazines are present on the platform.

5. Instant Blog: Fast and Simple Blog PHP Script


Instant Blog as the name suggests works on instant technologies. The script helps to load a blog ten times faster than any other platform. The script has SEO optimization and works with an immersive interface. This makes the platform easy to use and incorporates easy-to-use and simple layout formats.

The script has a powerful admin panel that allows the users to manage posts, categories, and users efficiently. The script also allows the access of dynamic forms and ensures that auto-embed URLs are also used.

6. phpBlog: News, Blog, and Magazine Script


The phpBlog is a multipurpose blogging script. This allows the users to incorporate in the system blogs, portals, company and agency websites, magazines, newspapers, and more. The system is built on a procedural framework and has a simple, lightweight, and responsive design.

The admin panel is also very powerful and can be used for a different point of access in the platform which allows the system to use different things inside the script like SEO, cms, in the platform.

7. Viavi News Magazine Blog Script


Viavi news magazine has a very stunning blogging interface, it is dedicated to news and magazine-focused blogs. The script has 12 customization layouts that can be used by the user to create different layouts and formats according to the requirement. The system is great for creating engagement of the user with blogs and also sharing through social media accounts.

8. Newspaper: Responsive News, Magazine and Blog CMS Script


The Newspaper is a script that is built to showcase solutions for news and blogs. The system has a responsive CMS system in the script that allows the clients to make efficient management of the system. The backend also has very impressive features that allow seamless navigation of the script.

The script has a built-in newsletter option that allows the users to send posts and messages whenever required.




9. Fibonacci: Laravel Portfolio and Blog CMS Script


If you are a web developer and need your own blog, Fibonacci is your savior. The system has a clean and easy to use developer platform with modern custom layouts. The script is responsive and has incorporated in itself the system of SEO to improve visibility. The script has an easy to use panel and allows the users to give interactive presentations. The system also incorporates homepage layouts, contact forms, modes, and other features.

PHP has seen huge popularity in terms of scripts like food delivery PHP script, blogging scripts, and others. So, if you are someone who wants to use blogging as a means of communication with the client. Go ahead and check the mentioned scripts and choose the one that best suits you.

About The Author :-


Hermit Chawla is an MD at AIS Technolabs which is a Web design and Development Company, helping global businesses to grow by PHP Script Development Company. I would love to share thoughts on Social Media Marketing Services and Game Design Development etc.