Thursday, 22 July 2021

Autocomplete Search in Laravel 8 using Typeahead.js


Autocomplete or Live Search is nice functionality, because it has give us auto suggestion or recommendations, when we have start type in input field. If you have not know but Autocomplete feature has provide helps to User in different ways like auto search suggestion when we have search some specific product or some specific category. So when we have start type then it has provide suggestion which has fetch from database and display in autocomplete search suggestion dropdown list.

Under this Laravel 8 tutorial, we will implement Autocomplete Search by using Typeahead.js library. So this is Laravel 8 Autocomplete tutorial in which you can find how to add Autocomplete Search feature in Laravel 8 Application by using Typeahead JS with Mysql database.

If you want to make Autocomplete Search feature for your web application, then typeahead.js is the best solution. Typeahead.js is a Javascript library which helps us to make an outstanding Autocomplete Search functionality in our Laravel 8 Application.

Now we have proceed for create Autocomplete Search Module in our Laravel 8 application. In this tutorial, we will create model and migration and add fake data in Mysql database and from that data we will fetch and display in autocomplete search suggestion in our Laravel 8 application. So here we will build dynamic Autocomplete Search in Laravel 8 using Typeahead JS. For this you have to follow following steps.


Autocomplete Search in Laravel 8 using Typeahead.js

How to Implement Dynamic Autocomplete Search in Laravel using Typeahead.js


  1. Step 1 : Download & Install Laravel Framework
  2. Step 2 : Make Database Connection
  3. Step 3 : Create User Table in Database
  4. Step 4 : Generate Fake Records
  5. Step 5 : Create Controller
  6. Step 6 : Create index() method in Controller
  7. Step 7 : Create Blade View File
  8. Step 8 : Create action() method in Controller
  9. Step 9 : Set Routes for Controller Method
  10. Step 10 : Start Development Server
  11. Step 11 : Check Output in Browser

Step 1 : Download & Install Laravel Framework


For build Autocomplete search feature, first we want to install latest version of Laravel framework. For this we have go to command prompt and run following command.


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


This command will create typeahead_autocomplete directory and under that directory it will download latest version of Laravel framework. After download Laravel framework, then after we have go into typeahead_autocomplete this directory. For this we have to run following command in command prompt.


cd typeahead_autocomplete


Step 2 : Make Database Connection


In second step we have make Mysql Database connection with our Laravel 8 application. For this we have to open .env file and under this we have to define MySQL credential which you can seen below.


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


Step 3 : Create User Table in Database


In third step, we have to create User table in Mysql database. So when we have download latest version of Laravel framework then by default User.php model class and users table migration file will be available under this Laravel framework. So for create users we have to go command prompt and run following command. This command will create users table in MySQL database.


php artisan migrate

Step 4 : Generate Fake Records


Once if you have create users table then under this steps we have to insert fake records under this table. For this we have to open database/seeders/DatabaseSeeder.php file and under this file we have to write following code.

database/seeders/DatabaseSeeder.php

<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;

use App\Models\User;

class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
        // \App\Models\User::factory(10)->create();

        User::factory(100)->create();
    }
}
?>


After this we have open command prompt and run following command. This command will insert 100 fake data under this users table in MySQL Database.


php artisan db:seed --force


Step 5 : Create Controller


In fifth steps, we have to create controller class under Laravel framework. For this we have to open command prompt and fun following command.


php artisan make:controller TypeaheadAutocompleteController

This command will create TypeaheadAutocompleteController.php controller class file in app/Http/Controllers folder. Under this file first we want to import User models class. For this we have to write following code at header of this class file.


use App\Models\User;


Step 6 : Create index() method in Controller


After create controller class file, now in step six, we need to create index() method under this class. So this method will load typeahead_autocomplete.blade.php file in browser.


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\User;

class TypeaheadAutocompleteController extends Controller
{
    function index()
    {
        return view('typeahead_autocomplete');
    }
}
?>





Step 7 : Create Blade View File


In this step 7, we have need to create blade view file for display html output in browser. So here we have create typeahead_autocomplete.blade.php under resources/views directory. In the blade view, we need to import Typeahead js and bootstrap 4 library for make autocomplete in Laravel 8 app.


<html>
    <head>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Typeahead JS Live Autocomplete Search in Laravel 8</title>
        <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://code.jquery.com/jquery-3.4.1.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.2/bootstrap3-typeahead.min.js" ></script>
    </head>
    <body>
        <div class="container">    
            <br />
            <h1 class="text-center text-primary">Typeahead JS Live Autocomplete Search in Laravel 8</h1>
            <br />
            <input type="text" name="user_name" id="user_name" class="form-control-lg" placeholder="Enter User Name..." />
        </div>
    </body>
</html>

<script>

var path = "{{ url('typeahead_autocomplete/action') }}";

$('#user_name').typeahead({

    source: function(query, process){

        return $.get(path, {query:query}, function(data){

            return process(data);

        });

    }

});

</script>


Step 8 : Create action() method in Controller


In steps 8, we have to crate action() method in Controller class file. Because this method will received ajax request from typeahead.js for fetch match data from database, and this method will send data to ajax request in JSON format.


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\User;

class TypeaheadAutocompleteController extends Controller
{
    function index()
    {
        return view('typeahead_autocomplete');
    }

    function action(Request $request)
    {
        $data = $request->all();

        $query = $data['query'];

        $filter_data = User::select('name')
                        ->where('name', 'LIKE', '%'.$query.'%')
                        ->get();

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



Step 9 : Set Routes for Controller Method


In steps 9, we need to set route for two method of controller class. For set route, we have to open routes/web.php file and under this file first we need to import TypeaheadAutocompleteController.php class file and then after write code for set route.


<?php

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\TypeaheadAutocompleteController;

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

Route::get('/typeahead_autocomplete', [TypeaheadAutocompleteController::class, 'index']);

Route::get('/typeahead_autocomplete/action', [TypeaheadAutocompleteController::class, 'action'])->name('typeahead_autocomplete.action');


Step 10 : Start Development Server


Once we have follow all above step, so here our Laravel 8 application is ready with Autocomplete Search feature. So for check output in browser, first we have need to start Laravel development server. For this we have to open command prompt and run following command. This command will start server and provide us base url of our Laravel application.


php artisan serve


Step 11 : Check Output in Browser


After start development server, now we want to check output in browser. So in browser we have hit following url for check Autocomplete Search in Laravel 8 application.


http://localhost:8000/typeahead_autocomplete


Conclusion


So under this tutorial, we have seen how easily we can implement Typeahead.js Autocomplete search in Laravel 8 framework. So making this Autocomplete Search feature, we have seen that it is very useful in our web application, because when we have type something then this feature has provide us suggestion related to text which we have type in input field, and user can get filter suggestion and from that suggestion user can select option.

Tuesday, 13 July 2021

How to Export Html Table to Excel Sheet using JavaScript


In this tutorial you can find the solution of How to Export or Download the HTML Table Data in Excel Sheet by using JavaScript. Exporting Data to Excel is required feature in our web application. Because by export data functionality will helps to download data from web application to different file format for offline use of data and for this excel format is an ideal for exporting data in file for offline use. There many tutorial we have published for export data to excel at server side scripting using PHP. But if we can perform at client-side for export data into Excel sheet, so it will reduce load on server. So for this for export data to excel , here we will use JavaScript for perform client-side export data to excel sheet.

The client-side export feature will makes our web application more user-friendly. So with the help of JavaScript, we can export HTML table data to Excel format without refresh of web page. Under this tutorial, you can learn How to export HTML table data to excel using JavaScript. In this tutorial, we will use SheetJS JavaScript Library for export HTML table data to Excel.


How to Export Html Table to Excel Sheet using JavaScript

Steps to Export HTML Table Data to Excel using JavaScript


  1. HTML Table Data:
  2. JavaScript Code:

1. HTML Table Data


For Export HTML data to Excel, here first we have to load some data in HTML table. So here we have make fetch employee table data and load in HTML table with table column like name, address, gender, designation and age. Here we have create HTML table with id employee_data. So this id we will use for fetch this HTML table data in JavaScript code. Under this HTML code we have make one button tag with id export_button, so when use has click on this button, then HTML table data will be download in Excel file format without refresh of web page using JavaScript.








<?php

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

$query = "SELECT * FROM tbl_employee ORDER BY name ASC";

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

?>

<!DOCTYPE HTML>
<html>
<head>
	<meta charset="utf-8" />
	<title>Export HTML table data to excel using JavaScript</title>
	<meta name="viewport" content="width=device-width, initial-scale=1" />
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

    <script type="text/javascript" src="https://unpkg.com/xlsx@0.15.1/dist/xlsx.full.min.js"></script>
</head>
<body>
    <div class="container">
    	<h2 class="text-center mt-4 mb-4">Export HTML table data to excel using JavaScript</h2>
    	<div class="card">
    		<div class="card-header">
    			<div class="row">
    				<div class="col col-md-6">Sample Data</div>
    				<div class="col col-md-6 text-right">
    					<button type="button" id="export_button" class="btn btn-success btn-sm">Export</button>
    				</div>
    			</div>
    		</div>
    		<div class="card-body">
    			<table id="employee_data" class="table table-striped table-bordered">
                    <tr>
                        <th>Name</th>
                        <th>Address</th>
                        <th>Gender</th>
                        <th>Designation</th>
                        <th>Age</th>
                    </tr>
                    <?php
                    foreach($result as $row)
                    {
                        echo '
                        <tr>
                            <td>'.$row["name"].'</td>
                            <td>'.$row["address"].'</td>
                            <td>'.$row["gender"].'</td>
                            <td>'.$row["designation"].'</td>
                            <td>'.$row["age"].'</td>
                        </tr>
                        ';
                    }
                    ?>
                </table>
    		</div>
    	</div>
    </div>
</body>
</html>





2. JavaScript Code


In this tutorial, we have use SheetJS JavaScript Library for export HTML table data to Excel using JavaScript. So first we have to include following SheetJS library link at header of this HTML web page.


<script type="text/javascript" src="https://unpkg.com/xlsx@0.15.1/dist/xlsx.full.min.js"></script>


In JavaScript code part, first we have make html_table_to_excel(type) function. This function has use SheetJS Library function and convert or Write HTML table data to Excel format and download in browser without refresh of web page.

Once function is ready then we have to called html_table_to_excel(type) function on button click event, so for trigger button click event, we have use addEventListener method. So when user has click on button then html_table_to_excel(type) function has been called with xlsx file type. So it will download HTML table data in .xlsx format Excel file in browser without refresh of web page at client-side.


function html_table_to_excel(type)
    {
        var data = document.getElementById('employee_data');

        var file = XLSX.utils.table_to_book(data, {sheet: "sheet1"});

        XLSX.write(file, { bookType: type, bookSST: true, type: 'base64' });

        XLSX.writeFile(file, 'file.' + type);
    }

    const export_button = document.getElementById('export_button');

    export_button.addEventListener('click', () =>  {
        html_table_to_excel('xlsx');
    });


Conclusion


This tutorial will helps you to add export feature of download HTML table data in Excel sheet without using third-party jQuery plugin or any server-side script. By follow this tutorial you can easily export HTML table data to Excel using minimal JavaScript code.


If you want to get complete source with .sql file, so please write your email address in comment box. We will send you complete source code file at your define email address.







Thursday, 8 July 2021

PHP jQuery Dynamic Selectpicker Dropdown box using Bootstrap 5


If you are beginner in Web application development field, then you have to know add or remove dynamic input fields feature is very useful, when in your web application there are multiple data has to be inserted in single click. So if you need to submit bulk data with multiple input field, then add or remove input field dynamically feature will help you. This is because if you have display some specific number of input fields at the loading of web page, and then after you have to use feature like add or remove input field dynamically, then it will increase your web application user friendlyness.

But in this tutorial, we will not only discuss dynamically add or remove simple input field like textbox or select box, but here we will dynamically add or remove advance select box by using Bootstrap 5 Select plugin with search feature. In this tutorial script will allows to users to add input field with Selectpicker dropdown list box in single click. So by adding Selectpicker select box which will extends our form functionality and it will make our form more productive. Under this tutorial, you can find how to add input fields with Selectpicker Select box dynamically using jquery and submit input fields and Selectpicker select box value using PHP.


PHP jQuery Dynamic Select Selectpicker Dropdown box using Bootstrap 5


Add or Remove Selectpicker Dropdown Select box fields dynamically


In this tutorial you can find the example which will show you add or remove multiple select picker dropdown box with other input field dynamically with jQuery and submit multiple input fields and select box data using Ajax with PHP. For understand the concept of Add or Remove Selectpicker select box with other input field, here we have use shopping cart example, in which user can add or remove input fields with Select picker select box in which user can search item unit and submit Shopping cart with multiple item data will be submitted at once using Ajax with PHP.







Bootstrap 5, Bootstrap 5 Select & jQuery Library


Under this tutorial, we have use Bootstrap 5 library for make input field and action button will look better, and for make searchable select box, here we have use Bootstrap 5 Select plugin, so by using this plugin user can able to search option under this select box, and jquery is used for implement add or remove input fields and select box fields dynamically. So for make this stylish feature, we need to add Bootstrap 4, Bootstrap 5 Select and jQuery library first at header of web page.


<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
		<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
		<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>

		<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-select@1.14.0-beta2/dist/css/bootstrap-select.min.css">

		<script src="https://cdn.jsdelivr.net/npm/bootstrap-select@1.14.0-beta2/dist/js/bootstrap-select.min.js"></script>

		<link rel="stylesheet" href="https://pro.fontawesome.com/releases/v5.10.0/css/all.css" integrity="sha384-AYmEC3Yw5cVb3ZcuHtOA93w35dYTsvhLPVnYs9eStHfGJvOvKxVfELGroGkvsg+p" crossorigin="anonymous"/>


HTML Code


Under HTML code first we have to create one form with id insert_form. We will submit form data using Ajax. Under this form for display input field or Select box dynamically, we have create one HTML table and under this table we will append input field dynamically using jQuery. And under this HTML code for display success or error message, we have create one span tag.


<form method="post" id="insert_form">
						<div class="table-repsonsive">
							<span id="error"></span>
							<table class="table table-bordered" id="item_table">
								<tr>
									<th>Enter Item Name</th>
									<th>Enter Quantity</th>
									<th>Select Unit</th>
									<th><button type="button" name="add" class="btn btn-success btn-sm add"><i class="fas fa-plus"></i></button></th>
								</tr>
							</table>
							<div align="center">
								<input type="submit" name="submit" id="submit_button" class="btn btn-primary" value="Insert" />
							</div>
						</div>
					</form>





jQuery Code


Under jQuery Script, we have make add_input_field(count) function, this function will be used for add dynamic input field and Select picker select box in item table.

First this function will be called on page load, so it will append one row with input field and Select picker dropdown box. But here we have use Bootstrap 5 Select plugin for convert simple select box into advance select box with feature like search option data. So for this we have to refresh data of Selectpicker select box by using $('.selectpicker').selectpicker('refresh'); code.

Then after for add more input field with Select picker dropdown box, we have to click on add button, so when we have click on add button, then it will again called add_input_field() function, and append new row with input field, and select picker select box with remove button, and here also we have to refresh data of select picker select box by using $('.selectpicker').selectpicker('refresh'); code.

Same way for remove single row of input field and select picker select box, we have to clickm on remove button, so when we have click on remove button, then it will remove that row of data.

And lastly for submit form data, so here we have first validate form data by using jquery and then after submit form data by using Ajax and it will submit form data to PHP script.


$(document).ready(function(){

	var count = 0;
	
	function add_input_field(count)
	{

		var html = '';

		html += '<tr>';

		html += '<td><input type="text" name="item_name[]" class="form-control item_name" /></td>';

		html += '<td><input type="text" name="item_quantity[]" class="form-control item_quantity" /></td>';

		html += '<td><select name="item_unit[]" class="form-control selectpicker" data-live-search="true"><option value="">Select Unit</option><?php echo fill_unit_select_box($connect); ?></select></td>';

		var remove_button = '';

		if(count > 0)
		{
			remove_button = '<button type="button" name="remove" class="btn btn-danger btn-sm remove"><i class="fas fa-minus"></i></button>';
		}

		html += '<td>'+remove_button+'</td></tr>';

		return html;

	}

	$('#item_table').append(add_input_field(0));

	$('.selectpicker').selectpicker('refresh');

	$(document).on('click', '.add', function(){

		count++;

		$('#item_table').append(add_input_field(count));

		$('.selectpicker').selectpicker('refresh');

	});

	$(document).on('click', '.remove', function(){

		$(this).closest('tr').remove();

	});

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

		event.preventDefault();

		var error = '';

		count = 1;

		$('.item_name').each(function(){

			if($(this).val() == '')
			{

				error += "<li>Enter Item Name at "+count+" Row</li>";

			}

			count = count + 1;

		});

		count = 1;

		$('.item_quantity').each(function(){

			if($(this).val() == '')
			{

				error += "<li>Enter Item Quantity at "+count+" Row</li>";

			}

			count = count + 1;

		});

		count = 1;

		$("select[name='item_unit[]']").each(function(){

			if($(this).val() == '')
			{

				error += "<li>Select Unit at "+count+" Row</li>";

			}

			count = count + 1;

		});

		var form_data = $(this).serialize();

		if(error == '')
		{

			$.ajax({

				url:"insert.php",

				method:"POST",

				data:form_data,

				beforeSend:function()
	    		{

	    			$('#submit_button').attr('disabled', 'disabled');

	    		},

				success:function(data)
				{

					if(data == 'ok')
					{

						$('#item_table').find('tr:gt(0)').remove();

						$('#error').html('<div class="alert alert-success">Item Details Saved</div>');

						$('#item_table').append(add_input_field(0));

						$('.selectpicker').selectpicker('refresh');

						$('#submit_button').attr('disabled', false);
					}

				}
			})

		}
		else
		{
			$('#error').html('<div class="alert alert-danger"><ul>'+error+'</ul></div>');
		}

	});
	 
});


Get Value of Input field and Selectpicker Select box in PHP


After Submitting form data using Ajax then at server side for get the value of multiple input field and Selectpicker select box data, so at PHP script we will use $_POST method for fetch value from input fields and select picker select box in PHP.


if(isset($_POST["item_name"]))
{

	include('database_connection.php');

	$order_id = uniqid();

	for($count = 0; $count < count($_POST["item_name"]); $count++)
	{

		$query = "
		INSERT INTO order_items 
        (order_id, item_name, item_quantity, item_unit) 
        VALUES (:order_id, :item_name, :item_quantity, :item_unit)
		";

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

		$statement->execute(
			array(
				':order_id'		=>	$order_id,
				':item_name'	=>	$_POST["item_name"][$count],
				':item_quantity'=>	$_POST["item_quantity"][$count],
				':item_unit'	=>	$_POST["item_unit"][$count]
			)
		);

	}

	$result = $statement->fetchAll();

	if(isset($result))
	{
		echo 'ok';
	}

}


If you want to get complete source with .sql file, so please write your email address in comment box. We will send you complete source code file at your define email address.







Monday, 5 July 2021

How to use Soft Delete to Restore Deleted Data in Laravel


In this Laravel tutorial we are going to learn How to use Soft Delete in Laravel framework. We will seen how can we restore deleted records and again we can see that records in our Laravel application with the help of soft delete.

So when we have use Soft Delete in our Laravel application so when we have delete data from our web application then that data is not deleted from database but that data we cannot see at our web application front-end side and at back-end side we can again recover and display or list in our application. So this things we will discuss under this tutorial by taking practical example how soft delete work in Laravel crud application.

How to Work Laravel Soft Delete


Suppose we have use Soft delete in Laravel web application, so when we have remove data from our application then that data is not actually removed from Mysql Database table. But current timestamp time has been updated at the deleted_at column. And when we have restore that deleted data then current timestamp value will be updated with nulled in deleted_at table column.

Please follow below step for how to implement soft delete in Laravel application for restore deleted records.


Preview


How to use Soft Delete to Restore Deleted Data in Laravel

Install Laravel Framework


For implement SoftDelete, first we need to download fresh copy of Laravel framework. So we have to go to command prompt and run following command.


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


This command will first make soft_delete directory and under that directory it will download fresh copy of Laravel framework.




Make Database Connection


After download latest version of Laravel framework, first we need to make databae connection. So for make database connection in Laravel application, we have to open .env file and under that file we have to define our MySQL database configuration details.


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


Create Model Class


Once you have make database connection in Laravel framework, then in next step we have to create one model class and migration file for create table in MySQL database. So for this, we have to run following command in command prompt.


php artisan make:model Post -m


This command will make Post.php models class file in app/Models directory and migration file under database/migrations folder. First we have open migrations directory file and under that file, we have to define table column details which you can seen below.

database/migrations/2021_07_05_065844_create_posts_table.php

<?php

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

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

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



After this, we have to run following command in command prompt.


php artisan migrate

This command will run migration process and it will create posts table in your mysql database with following table column.


How to use Soft Delete to Restore Deleted Data in Laravel

Add SoftDelete in Models Class


Now in this steps we have to add Soft Delete in our Post.phpmodels class. But before we need create migrations for adding soft delete to posts table. So for this we have to run following command in command prompt.


php artisan make:migration add_sorft_delete_column


This above command will create new migration file at database/migrations directory which you can seen below.

database/migrations/new_migration_file.php

<?php

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

class AddSorftDeleteColumn extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('posts', function(Blueprint $table){
            $table->softDeletes();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('posts', function(Blueprint $table){
            $table->dropSoftDeletes();
        });
    }
}



After this we have to run migration command in command prompt.


php artisan migrate


Once you have run this command, then it will add deleted_at table column to posts table which you can seen below.


How to use Soft Delete to Restore Deleted Data in Laravel


Now for add dummy data, you have to run following sql script, so it will insert some dummy data in posts table.


INSERT INTO `posts` (`id`, `title`, `description`, `created_at`, `updated_at`, `deleted_at`) VALUES
(1, 'Ajax Pagination using PHP with JavaScript', 'Ajax Pagination using PHP with JavaScript', '2021-07-02 07:27:03', '2021-07-05 01:17:26', NULL),
(2, 'Ajax Live Data Search using JavaScript with PHP', 'Ajax Live Data Search using JavaScript with PHP', '2021-07-02 07:27:03', '2021-07-05 01:17:26', NULL),
(3, 'Dynamic Pie, Doughnut & Bar Chart in PHP using Chart.js', 'Dynamic Pie, Doughnut & Bar Chart in PHP using Chart.js', '2021-07-02 07:27:03', '2021-07-03 06:35:02', NULL),
(4, 'How to Create Review & Rating Page in PHP with Ajax', 'How to Create Review & Rating Page in PHP with Ajax', '2021-07-02 07:27:03', '2021-07-02 07:27:03', NULL),
(5, 'Submit Form without Page Refresh using JavaScript with PHP', 'Submit Form without Page Refresh using JavaScript with PHP', '2021-07-02 07:27:03', '2021-07-02 07:27:03', NULL),
(6, 'How to Add Custom Select Box pagination in jQuery DataTable with Ajax PHP', 'How to Add Custom Select Box pagination in jQuery DataTable with Ajax PHP', '2021-07-02 07:27:03', '2021-07-02 07:27:03', NULL),
(7, 'How to Export Data in Excel using Codeigniter 4', 'How to Export Data in Excel using Codeigniter 4', '2021-07-02 07:27:03', '2021-07-02 07:27:03', NULL),
(8, 'Laravel 8 Tutorial - Join Multiple Table using Eloquent Model	', 'Laravel 8 Tutorial - Join Multiple Table using Eloquent Model	', '2021-07-02 07:27:03', '2021-07-02 07:27:03', NULL),
(9, 'Toast Notification for Check Internet Connection with Bootstrap 4 & javascript	', 'Toast Notification for Check Internet Connection with Bootstrap 4 & javascript	', '2021-07-02 07:27:03', '2021-07-02 07:27:03', NULL),
(10, 'Dynamic Dependent Dropdown using Ajax in Codeigniter 4	', 'Dynamic Dependent Dropdown using Ajax in Codeigniter 4', '2021-07-02 07:27:04', '2021-07-02 07:27:04', NULL);


Next we want to add soft delete facade in our Post model, you can below find source code for add SoftDelete facade in Post models class.

app/Models/Post.php

<?php

namespace App\Models;

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

class Post extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = ['title', 'description'];

    protected $dates = ['deleted_at'];
}





Create Controller Class


In next step, we have to create PostController and add following code in that controller file. So for create controller class file, we have need to run following command in command prompt.


php artisan make:controller PostController


This command will create PostController.php file at app/Http/Controllers directory. So need to open that file and add following code.

app/Http/Controllers/PostController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Models\Post;

class PostController extends Controller
{
    public function index(Request $request)
    {
        $posts = Post::get();

        if($request->has('view_deleted'))
        {
            $posts = Post::onlyTrashed()->get();
        }

        return view('post', compact('posts'));
    }

    public function delete($id)
    {
        Post::find($id)->delete();

        return back()->with('success', 'Post Deleted successfully');
    }

    public function restore($id)
    {
        Post::withTrashed()->find($id)->restore();

        return back()->with('success', 'Post Restore successfully');
    }

    public function restore_all()
    {
        Post::onlyTrashed()->restore();

        return back()->with('success', 'All Post Restored successfully');
    }
}



Under this controller class file we have make following method.

index(Request $request) : This method will fetch data on condition, suppose there is view_deleted variable has been received in url then it has only fetch deleted data otherwise it has fetch all data from database and send to view blade file.

delete($id) : This method has received request for delete data and it has received id in request, so based on value of that id it will perform soft delete operation.

restore($id) : This method has received get request for restore single data, so with restore request it has received id and that id data has been restore.

restore_all() : This method has received get request for restore all deleted data.

Create View Blade File


In Laravel framework for display output on browser we need to create blades file for display data on web page. In this example we have create blade file resources/views/post.blade.php directory.


<html>
    <head>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>How to Use Soft Delete in Laravel</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 Use Soft Delete in Laravel</h1>
            <br />
            @if(session()->has('success'))

                <div class="alert alert-success">
                    {{ session()->get('success') }}
                </div>

            @endif
            <div class="card">
                <div class="card-header">
                    <div class="row">
                        <div class="col col-md-6">Sample Data</div>
                        <div class="col col-md-6 text-right">
                            @if(request()->has('view_deleted'))

                            <a href="{{ route('post.index') }}" class="btn btn-info btn-sm">View All Post</a>

                            <a href="{{ route('post.restore_all') }}" class="btn btn-success btn-sm">Restore All</a>

                            @else

                            <a href="{{ route('post.index', ['view_deleted' => 'DeletedRecords']) }}" class="btn btn-primary btn-sm">View Deleted Post</a>

                            @endif
                            
                        </div>
                    </div>
                </div>
            
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-bordered table-striped">
                            <thead>
                                <tr>
                                    <th>Id</th>
                                    <th>Title</th>
                                    <th>Description</th>
                                    <th>Action</th>
                                </tr>
                            </thead>
                            <tbody>
                            @if(count($posts) > 0)
                                @foreach($posts as $row)

                                <tr>
                                    <td>{{ $row->id }}</td>
                                    <td>{{ $row->title }}</td>
                                    <td>{{ $row->description }}</td>
                                    <td>
                                        @if(request()->has('view_deleted'))

                                            <a href="{{ route('post.restore', $row->id) }}" class="btn btn-success btn-sm">Restore</a>
                                        @else
                                            <form method="post" action="{{ route('post.delete', $row->id) }}">
                                                @csrf
                                                <input type="hidden" name="_method" value="DELETE" />
                                                <button type="submit" class="btn btn-danger btn-sm">Delete</button>
                                            </form>
                                        @endif
                                    </td>
                                </tr>

                                @endforeach
                            @else
                                <tr>
                                    <td colspan="4" class="text-center">No Post Found</td>
                                </tr>

                            @endif
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </body>
</html>


Set Route


Under this step we need to set route for PostController.php class method. So for set file we need to open routes/web.php file.

routes/web.php

<?php

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\PostController;

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


Route::get('post', [PostController::class, 'index'])->name('post.index');

Route::delete('post/{id}', [PostController::class, 'delete'])->name('post.delete');

Route::get('post/restore/one/{id}', [PostController::class, 'restore'])->name('post.restore');

Route::get('post/restore_all', [PostController::class, 'restore_all'])->name('post.restore_all');


Run Laravel Application


After follow all above step now we want to check Laravel application output. So first we have run server. So for this we have to run following command in command prompt.


php artisan serve

This command will star server and provide us base url of our Laravel application. So for check output of above code, we have to hit following url in browser.


http://127.0.0.1:8000/post


So this are the complete process for how to use SoftDelete in Laravel and implement Restore Deleted Records feature in your Laravel application. We hope this tutorial will help you to learn something new in Laravel framework.

Download Complete Source Code


If you want to get complete source with .sql file, so please write your email address in comment box. We will send you complete source code file at your define email address.





Tuesday, 29 June 2021

File Upload in JavaScript using Fetch API with PHP


In this post, you can learn How to upload file to the server using JavaScript Fetch API with PHP script which we have explained in step by step process in a very simple way.

In the web based application uploading file on to a server from web page is one of the very common and required functionality in our web application. So if you have search on internet then there are lots of JavaScript libraries are available for handle the file upload from our local computer to online server.

But for simple file upload feature, we have to use any libraries, then this upload library will increase extra load on our website and this upload feature we can easily handled by using pure vanilla JavaScript by using Fetch API. If you have not know but Fetch API is a promised based latest replacement of XHR Ajax request for making HTTP requests send to browser. So here we will use JavaScript native Fetch API for upload file on to server with PHP script.


File Upload in JavaScript using Fetch API with PHP







File Upload using Fetch


First Add the following HTML input file field to your website.


<input type="file" name="sample_image" />


Below this we have to create one division tag, and under this tag, we will display validation error or upload image file.


<div class="text-center" id="uploaded_image"></div>

After add file tag and one division tag for display output in to website, next we want to add event listner on to input file tag, which will be trigger when we have select file from local computer.


const sample_image = document.getElementsByName('sample_image')[0];

sample_image.addEventListener('change', () => {

	upload_image(sample_image.files[0]);

});


After add event listner on selecting of file and it will called upload_image() function, so we have to make upload_image() function which will upload selecting file to server with PHP script.





Validate File Type and Size before Uploading


Before uploading file on to server first we want to validate file type and file size before uploading of file. So in this example we want to upload only .jpg and .png file type image on to server and image file size mus not exceeds 2MB. So for this things we have write following javascript code.


const upload_image = (file) => {

	if(!['image/jpeg', 'image/png'].includes(file.type))
	{
		document.getElementById('uploaded_image').innerHTML = '<div class="alert alert-danger">Only .jpg and .png image are allowed</div>';

		document.getElementsByName('sample_image')[0].value = '';

		return;
	}

	if(file.size > 2 * 1024 * 1024)
	{
		document.getElementById('uploaded_image').innerHTML = '<div class="alert alert-danger">File must be less than 2 MB</div>';

		document.getElementsByName('sample_image')[0].value = '';

		return;
	}
        ............
}


Once selected file type and file size have been validated then this javascript must be prceeds for send file to server. So for send file to server here we have use FormData interface and under this we will store selected file And for send file to server here we have use JavaScript fetch() API which will send file to server and on success of image upload it will display uploaded image on web page.


const upload_image = (file) => {

	// check file type

	if(!['image/jpeg', 'image/png'].includes(file.type))
	{
		document.getElementById('uploaded_image').innerHTML = '<div class="alert alert-danger">Only .jpg and .png image are allowed</div>';

		document.getElementsByName('sample_image')[0].value = '';
		
        return;
    }

    // check file size (< 2MB)
    if(file.size > 2 * 1024 * 1024)
    {
    	document.getElementById('uploaded_image').innerHTML = '<div class="alert alert-danger">File must be less than 2 MB</div>';

    	document.getElementsByName('sample_image')[0].value = '';
        return;
    }

    const form_data = new FormData();

    form_data.append('sample_image', file);

    fetch("upload.php", {
    	method:"POST",
    	body : form_data
    }).then(function(response){
    	return response.json();
    }).then(function(responseData){

    	document.getElementById('uploaded_image').innerHTML = '<div class="alert alert-success">Image Uploaded Successfully</div> <img src="'+responseData.image_source+'" class="img-thumbnail" />';

    	document.getElementsByName('sample_image')[0].value = '';

    });

    
}


Server Side Handling File Uploading using PHP


In this example we have use PHP script for handling file upload on server side. so here we have write PHP script in upload.php file. This file will received request for upload file on to server. This script will fetch select file property from $_FILES variable and then after upload file in images folder using PHP move_uploaded_file() function.


if(isset($_FILES['sample_image']))
{

	$extension = pathinfo($_FILES['sample_image']['name'], PATHINFO_EXTENSION);

	$new_name = time() . '.' . $extension;

	move_uploaded_file($_FILES['sample_image']['tmp_name'], 'images/' . $new_name);

	$data = array(
		'image_source'		=>	'images/' . $new_name
	);

	echo json_encode($data);

}


Conclusion


So in this tutorial we have seen that Combination of FormData Object and JavaScript Fetch API are implementing our file upload task very easy way and with the help of both we can avoid reloading of whole page in order to increase our user experience. So by using Fetch API we can upload image without refresh of web page with PHP script and here we can perform HTTP request using JavaScript Fetch API and send file to server using FormData object and upload file using PHP script.

If you want to get complete source with .sql file, so please write your email address in comment box. We will send you complete source code file at your define email address.