Thursday, 18 April 2019

Live CSV File Data Editing and Importing in PHP using Ajax jQuery



This is very interesting post, in which we have covered topic like Uploading CSV file data and then after before import into Mysql table we can edit CSV file data on web page by using jquery Ajax with PHP. Now what are benefits of this feature, because suppose we want to edit CSV file data then we can directly edit into CSV file and then after we can proceed for importing. But suppose you don't know there is some spelling error or any information is wrong in CSV file data and you have start upload CSV file for import data then you cannot stop importing process and wrong data will be directly import into Mysql table. But in this feature when you have upload CSV file for importing into Mysql table then on web page first it will display all CSV file data on web page in table format and you can edit any table column data before importing. So you after uploading file you can check all CSV file data on web page and if there is any wrong data is found then you can edit them and then after you can import into Database by using PHP with Ajax jQuery.

In Current Web Development, there are new and new innovation has been developed for reducing error. So, this feature also is one innovation for importing data through CSV file. Because here data has been verified by two times and if any wrong information has been then we can Live Edit that CSV file data before importing. We all know CSV file format is widely used for import and export of data from any web application. Then if you have build any enterprise level web application and in that you have import data from CSV file then this feature will reduce human work, because we can edit CSV file data after uploading CSV file and before importing into database. So, this feature will reduce importing of wrong data into Database. So, here we have make one more tutorial on Live CSV file data editing and then after importing in Mysql Database by using PHP with Ajax jQuery.






index.php


This is then main file of this tutorial, In this find HTML code and jQuery Ajax code. In HTML code we have make one form in which we have define on file tag for select CSV file and upload button for send CSV file to server. And in jQuery Ajax code you can see below we have write jQuery code on two button click event.

First button click event will send selected CSV file to fetch.php file. For send file data to server, here we have use new FormData() object. After success of Ajax request it will received data in JSON format, and that data will be converted into HTML table format and display on web page. With table it will also make import button with id import_data will also make for import data into Mysql table. In student name table column has attribute like class="student_name" and student phone table column has attribute like class="student_phone". So, this column data will be fetch from jQuery code, and this two column will be editable by using contenteditable attribute.

In second jQuery click event has write on Import button, so when we have click on import button then this code will execute. In this first it has fetch data from attribute class and store under local variable in array format. Then after that local variable value will be send to PHP script by using Ajax request. Ajax request will send request to import.php file for import data into Database. After successfully importing of data it will display success message on web page.





<!DOCTYPE html>
<html>
 <head>
  <title>CSV File Editing and Importing in PHP</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
  <style>
  .box
  {
   max-width:600px;
   width:100%;
   margin: 0 auto;;
  }
  </style>
 </head>
 <body>
  <div class="container">
   <br />
   <h3 align="center">CSV File Editing and Importing in PHP</h3>
   <br />
   <form id="upload_csv" method="post" enctype="multipart/form-data">
    <div class="col-md-3">
     <br />
     <label>Select CSV File</label>
    </div>  
                <div class="col-md-4">  
                    <input type="file" name="csv_file" id="csv_file" accept=".csv" style="margin-top:15px;" />
                </div>  
                <div class="col-md-5">  
                    <input type="submit" name="upload" id="upload" value="Upload" style="margin-top:10px;" class="btn btn-info" />
                </div>  
                <div style="clear:both"></div>
   </form>
   <br />
   <br />
   <div id="csv_file_data"></div>
   
  </div>
 </body>
</html>

<script>

$(document).ready(function(){
 $('#upload_csv').on('submit', function(event){
  event.preventDefault();
  $.ajax({
   url:"fetch.php",
   method:"POST",
   data:new FormData(this),
   dataType:'json',
   contentType:false,
   cache:false,
   processData:false,
   success:function(data)
   {
    var html = '<table class="table table-striped table-bordered">';
    if(data.column)
    {
     html += '<tr>';
     for(var count = 0; count < data.column.length; count++)
     {
      html += '<th>'+data.column[count]+'</th>';
     }
     html += '</tr>';
    }

    if(data.row_data)
    {
     for(var count = 0; count < data.row_data.length; count++)
     {
      html += '<tr>';
      html += '<td class="student_name" contenteditable>'+data.row_data[count].student_name+'</td>';
      html += '<td class="student_phone" contenteditable>'+data.row_data[count].student_phone+'</td></tr>';
     }
    }
    html += '<table>';
    html += '<div align="center"><button type="button" id="import_data" class="btn btn-success">Import</button></div>';

    $('#csv_file_data').html(html);
    $('#upload_csv')[0].reset();
   }
  })
 });

 $(document).on('click', '#import_data', function(){
  var student_name = [];
  var student_phone = [];
  $('.student_name').each(function(){
   student_name.push($(this).text());
  });
  $('.student_phone').each(function(){
   student_phone.push($(this).text());
  });
  $.ajax({
   url:"import.php",
   method:"post",
   data:{student_name:student_name, student_phone:student_phone},
   success:function(data)
   {
    $('#csv_file_data').html('<div class="alert alert-success">Data Imported Successfully</div>');
   }
  })
 });
});

</script>


fetch.php


This PHP script has received Ajax request for fetch selected CSV file data from Ajax. Here first it has open CSV file by using fopen() function, then after it has read first line which will be table column of CSV file by using fgetcsv() method and store under local variable. After this for read all CSV file data it has use while loop with fgetcsv() method and it has read CSV file data and store data under local variable in array format. And lastly for send response to Ajax request in json format, it has use json_encode() method.


<?php

//fetch.php

if(!empty($_FILES['csv_file']['name']))
{
 $file_data = fopen($_FILES['csv_file']['tmp_name'], 'r');
 $column = fgetcsv($file_data);
 while($row = fgetcsv($file_data))
 {
  $row_data[] = array(
   'student_name'  => $row[0],
   'student_phone'  => $row[1]
  );
 }
 $output = array(
  'column'  => $column,
  'row_data'  => $row_data
 );

 echo json_encode($output);

}

?>


import.php


This script has received Ajax request for insert data into mysql table. First it has verify that there is any ajax has been received for not by using isset() function. If it has received data then it will make database connection and then after it has store array of data store under local variable. For generate multiple insert data query it has loop and after generating multiple insert query it has execute all query at the same time. So, this way it will insert or import multiple data at the same time.


<?php

//import.php

if(isset($_POST["student_name"]))
{
 $connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");
 $student_name = $_POST["student_name"];
 $student_phone = $_POST["student_phone"];
 for($count = 0; $count < count($student_name); $count++)
 {
  $query .= "
  INSERT INTO tbl_student(student_name, student_phone) 
  VALUES ('".$student_name[$count]."', '".$student_phone[$count]."');
  
  ";
 }
 $statement = $connect->prepare($query);
 $statement->execute();
}

?>


Database



--
-- Database: `testing`
--

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

--
-- Table structure for table `tbl_student`
--

CREATE TABLE `tbl_student` (
  `student_id` int(11) NOT NULL,
  `student_name` varchar(250) NOT NULL,
  `student_phone` varchar(20) NOT NULL,
  `image` varchar(255) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

--
-- Indexes for table `tbl_student`
--
ALTER TABLE `tbl_student`
  ADD PRIMARY KEY (`student_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `tbl_student`
--
ALTER TABLE `tbl_student`
  MODIFY `student_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;



Monday, 15 April 2019

Dynamically Add / Remove input fields in Laravel 5.8 using jQuery Ajax



Hi, If you want to use Laravel 5.8 framework for your web development then here we have come with one more advance level of web development topic like How to Add or remove HTML input fields dynamically using jQuery and how to save multiple records in Laravel 5.8 by using Ajax. So, here we have share one more topic on Laravel 5.8 and in this part you can learn how to add more fields using jQuery in Laravel 5.8 application, and for validate dynamically generated input fields we have also implement validation on dynamic generated fields also by using Laravel 5.8 Validator class. So, if you have use Laravel 5.8 for website development purpose and if you add feature like insert or save multiple records at the same time in Laravel 5.8 with Ajax, then this post will help you because in this post we hvae step by step covered How to add or remove textbox dynamically with jQuery and then after by using Ajax with Laravel 5.8 we have save multiple records in Mysql database.

If you are web developer and then in web development we need to sometimes required to insert or save multiple records in Mysql database at the same time. For generate multiple records we want to make multiple fields, for generate dynamic multiple fields here we have use jquery as front-end with Laravel 5.8 application. One of our previous post, we have already covered Add or remove dynamic input fields by using jQuery with PHP. But here we need to do Add or remove dynamically generated fields in jQuery in Laravel 5.8 application. Because this is very useful feature in web application by doing multiple operation in single click or insert or save multiple data into mysql database in single click on Laravel 5.8 application. Here you can also learn how to validate multiple input fields data with same data in Laravel 5.8 validator class. And here also you can learn how to insert or save or add multiple data in Laravel 5.8 application.






Step 1 - Download Laravel 5.8


First we need to download Laravel 5.8 application. For this we have to go to command prompt and write following command. It will download Laravel 5.8 application in your define folder.


composer create-project laravel/laravel=5.8 ajax-crud --prefer-dist


Step 2 - Make Database connection


After install of Laravel 5.8 application, first we wanted to make Mysql database connection. For this you have to open .env file and in that file you have to define Mysql database configuration.


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


Step 3 - Create Table from Laravel 5.8


After making of Mysql database, now we want to create table in Mysql database from Laravel 5.8 application. For this we need to go to command prompt and write following command.


php artisan make:migration create_dynamic_field --create=dynamic_fields

This command will make migration file under database/migarations folder. In that file you have to define table column defination details, which you can find below.


<?php

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

class CreateDynamicField extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('dynamic_fields', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('first_name');
            $table->string('last_name');
            $table->timestamps();
        });
    }

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


Now we want to migrate above table defination from Laravel 5.8 application to Mysql database. For this we have to go to command prompt and write following command. This command will make dynamic_fields table under Mysql database.


php artisan migrate


Step 4 - Create Model


For create model under Laravel 5.8 application, we have to go to command prompt and write following command. This command will make DynamicField.php modal file under app folder.


php artisan make:model DynamicField -m


In app/DynamicField.php file we have to define table column name on which we need for database operation.


<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class DynamicField extends Model
{
    protected $fillable = [
        'first_name', 'last_name'
    ];
}





Step 5 - Create Controller


Controller is the heart of Laravel 5.8 application because it has handle all http request. First we want to make controller, so we have to go to command prompt and write following command. It will make DynamicFieldController.php file under app/Http/Controllers folder.


php artisan make:controller DynamicFieldController


In this controller file you can see below in which we have add two statement in the header. First is use App\DynamicField is for use DynamicField.php modal file use here and second Validator is for use Laravel 5.8 validator class for validate form data. In this controller we have make two method which you can see below.

index() - This is root method of this controller and it will load dynamic_field.blade.php file on web browser as an output.

insert() - This method has received ajax request for insert multiple data. Under this method first it has validate multiple form data of same name. So, here question aris how to validate multiple form data of same name in Laravel 5.8, so here we have add * sign with input field name, which has been used when we have validate multiple form data of the same name in Laravel 5.8 application. If suppose there is any form validation error has been occur then it will send validation error to ajax request in JSON format by using response() method. But suppose there is no any validation error occur then it will continue execute. After this there one more question aris how to insert multiple data in Laravel 5.8 application. So here we have store multiple data in local variable in array format and by using insert() method of modal class, it will insert or save multiple data in Laravel 5.8 application.


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\DynamicField;
use Validator;

class DynamicFieldController extends Controller
{
    function index()
    {
     return view('dynamic_field');
    }

    function insert(Request $request)
    {
     if($request->ajax())
     {
      $rules = array(
       'first_name.*'  => 'required',
       'last_name.*'  => 'required'
      );
      $error = Validator::make($request->all(), $rules);
      if($error->fails())
      {
       return response()->json([
        'error'  => $error->errors()->all()
       ]);
      }

      $first_name = $request->first_name;
      $last_name = $request->last_name;
      for($count = 0; $count < count($first_name); $count++)
      {
       $data = array(
        'first_name' => $first_name[$count],
        'last_name'  => $last_name[$count]
       );
       $insert_data[] = $data; 
      }

      DynamicField::insert($insert_data);
      return response()->json([
       'success'  => 'Data Added successfully.'
      ]);
     }
    }
}


Step 6 - Create View file


In this post we have create dynamic_field.blade.php file under resources/views folder. Under this file for generate dynamic input field we have use jQuery code. By using jQuery here it will dynamically generate html input fields. For submit form data here we have use Ajax request, by using ajax request it will send form data to controller method.


<html>
 <head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Laravel 5.8 - DataTables Server Side Processing using Ajax</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
 </head>
 <body>
  <div class="container">    
     <br />
     <h3 align="center">Dynamically Add / Remove input fields in Laravel 5.8 using Ajax jQuery</h3>
     <br />
   <div class="table-responsive">
                <form method="post" id="dynamic_form">
                 <span id="result"></span>
                 <table class="table table-bordered table-striped" id="user_table">
               <thead>
                <tr>
                    <th width="35%">First Name</th>
                    <th width="35%">Last Name</th>
                    <th width="30%">Action</th>
                </tr>
               </thead>
               <tbody>

               </tbody>
               <tfoot>
                <tr>
                                <td colspan="2" align="right">&nbsp;</td>
                                <td>
                  @csrf
                  <input type="submit" name="save" id="save" class="btn btn-primary" value="Save" />
                 </td>
                </tr>
               </tfoot>
           </table>
                </form>
   </div>
  </div>
 </body>
</html>

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

 var count = 1;

 dynamic_field(count);

 function dynamic_field(number)
 {
  html = '<tr>';
        html += '<td><input type="text" name="first_name[]" class="form-control" /></td>';
        html += '<td><input type="text" name="last_name[]" class="form-control" /></td>';
        if(number > 1)
        {
            html += '<td><button type="button" name="remove" id="" class="btn btn-danger remove">Remove</button></td></tr>';
            $('tbody').append(html);
        }
        else
        {   
            html += '<td><button type="button" name="add" id="add" class="btn btn-success">Add</button></td></tr>';
            $('tbody').html(html);
        }
 }

 $(document).on('click', '#add', function(){
  count++;
  dynamic_field(count);
 });

 $(document).on('click', '.remove', function(){
  count--;
  $(this).closest("tr").remove();
 });

 $('#dynamic_form').on('submit', function(event){
        event.preventDefault();
        $.ajax({
            url:'{{ route("dynamic-field.insert") }}',
            method:'post',
            data:$(this).serialize(),
            dataType:'json',
            beforeSend:function(){
                $('#save').attr('disabled','disabled');
            },
            success:function(data)
            {
                if(data.error)
                {
                    var error_html = '';
                    for(var count = 0; count < data.error.length; count++)
                    {
                        error_html += '<p>'+data.error[count]+'</p>';
                    }
                    $('#result').html('<div class="alert alert-danger">'+error_html+'</div>');
                }
                else
                {
                    dynamic_field(1);
                    $('#result').html('<div class="alert alert-success">'+data.success+'</div>');
                }
                $('#save').attr('disabled', false);
            }
        })
 });

});
</script>


Step 7 - Set Route


In Laravel 5.8, we need to set route of all controller method which we have make. For this we have to open routes/web.php file and define following code for set route.


Route::get('dynamic-field', 'DynamicFieldController@index');

Route::post('dynamic-field/insert', 'DynamicFieldController@insert')->name('dynamic-field.insert');


Step 8 - Run Laravel 5.8 application


For run Laravel 5.8 application, we have to go to command prompt and write following command. This command will start Laravel 5.8 application and give you base url of your Laravel 5.8 application.


php artisan serve


For check output in browser you have to write following url in your browser tab.


http://127.0.0.1:8000/dynamic-field




Thursday, 4 April 2019

Laravel 5.8 Ajax Crud Tutorial using DataTables

Part 1




Part 2




Part 3




Part 4




After Learning Simple CRUD (Create, Read, Update, Delete) operation in Laravel 5.8 with file upload, Now we have start learning advance level Crud Application in Laravel 5.8 by using Ajax with jQuery DataTables and Bootstrap Modal. So, user can perform all Crud operation on same without refresh of web page. Because here it will make single page Ajax Crud Application with File Upload in Laravel 5.8 by jQuery DataTables server side processing and form operation done by using Bootstrap modal.

For make Laravel 5.8 Crud Application using Ajax with DataTables and Bootstrap model. So first for use DataTables with Laravel 5.8, here we have will use Yajra DataTables package. By using Yajra Laravel DataTables plugin we can easily implement Server Side Processing of Data in Laravel 5.8 framework. So, User can list all records in tabular formate with different features like pagination of data, sorting of data and filter or search of data.

Same way for perform all Insert Update Delete data using Ajax in Laravel 5.8 framework. Here we will use Bootstrap modal. By using Bootstrap modal, we will make form in modal, because modal will pop up Insert data or edit data form on web page. So, user can perform all add edit delete data operation on single page in Laravel 5.8 using Ajax. Below you can step by step process of implementing Ajax Crud tutorial in Laravel 5.8 using Yajra DataTables package and Bootstrap modal.


Laravel 5.8 Ajax Crud Tutorial using DataTables



Step 1 - Install Laravel 5.8


First we want to Download Laravel 5.8 version for developing Crud application using Ajax. For this you have to open your terminal or command prompt and write below command. It will download Laravel 5.8 in your define directory.


composer create-project laravel/laravel=5.8 ajax-crud --prefer-dist


Step 2 - Laravel 5.8 Database Connection


Once Laravel 5.8 has been downloaded then after we have to make Database connection. For this first you have to open config/database.php and define Mysql Database configuration.



.......

'mysql' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'testing'),
            'username' => env('DB_USERNAME', 'root'),
            'password' => env('DB_PASSWORD', ''),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'prefix_indexes' => true,
            'strict' => true,
            'engine' => null,
            'options' => array_filter([
                PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
            ]),
        ],

........


After this you have to open .env file and in that file also you have to define Mysql Database configuration, which you can find below.



.......

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

........


Step 3 - Create Table


For Create Crud Application, first we have to create Mysql table. For create Mysql table from Laravel 5.8 application we have to write following artisan command in your command prompt.


php artisan make:migration create_ajax_cruds_table --create=ajax_cruds


Above command will command create migration file in database/migrations folder. In that file we have to define table column which you want to define in Mysql table. Below you can find source code of migration file.


<?php

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

class CreateAjaxCrudsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('ajax_cruds', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('first_name');
            $table->string('last_name');
            $table->string('image');
            $table->timestamps();
        });
    }

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


Lastly for create Mysql table in your Database, you have to write following command in your terminal or command prompt. It will create ajax_cruds table in your define Database.


php artisan migrate


Step 4 - Create Model in Laravel 5.8


Now we want to make Model in Laravel 5.8, For this you have to write following command in your terminal or command prompt. It will create model file here app/AjaxCrud.php.


php artisan make:model AjaxCrud -m


Under this app/AjaxCrud.php file, you have to define table column for database operation which source code you can find below.


<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class AjaxCrud extends Model
{
    protected $fillable = [
     'first_name', 'last_name', 'image'
    ];
}


Step 5 - Install Yajra DataTabbles Package in Laravel 5.8


For use jQuery DataTables plugin in Laravel 5.8, for this first we want to install Yajra DataTables plugin in Laravel 5.8 application. For this we have to write following command in your computer terminal or command prompt.


composer require yajra/laravel-datatables-oracle


Above command will download Yajra DataTables package in your Laravel 5.8 application. For use of Yajra DataTables package in Laravel 5.8 framework, we have to set this package providers and alias details.


.....
'providers' => [
 ....
 Yajra\Datatables\DatatablesServiceProvider::class,
]
'aliases' => [
 ....
 'Datatables' => Yajra\Datatables\Facades\Datatables::class,
]
.....


Lastly we want to publish this Yajra DataTables package, for this we have to write following command.


php artisan vendor:publish





Step 6 - Create Controller in Laravel 5.8


Controller mostly used for handle HTTP request. Create new controller in Laravel 5.8 framework, we have to write following command.


php artisan make:controller AjaxCrudController --resource


This command will create AjaxCrudController.php file in app/Http/Controllers folder. In this controller file you can find all in build required method for do Crud operation. Under this controller for use AjaxCrud model, first we have to define use App\AjaxCrud; this statement at the header of the AjaxCrudController.php file.

index() - This is the root method of this controller. This method will received Ajax request for load data in jQuery DataTables plugin. If this method received ajax request then it will load data in jQuery DataTables plugin. In this ajax block you can find yajra datatables package code.

store() - For Insert Data into Mysql table using ajax in Laravel 5.8, here we have use store() method of AjaxCrudController.php. This method will received Ajax request for insert or add data. Under this method first it has validate for data. If there is any validation fails then it will send response to ajax request in JSON format. But there is no any validation fails then it will continue execution of code and first it will upload profile image of user and then after it will insert data into mysql table. And lastly it will send json response to ajax request.

edit() - This method is used for fetch single row of data from mysql table, and send data to ajax request in json formate which will be display under Bootstrap modal form.

update() - This method has received ajax request for update existing mysql table data. In this method first it check user has select profile image or not. If User is select image then in this method it will validate form data with selected file is image or not. But Suppose user has not select image then it will only validate textbox data only. If there is any validation error occur then it will send data to ajax request in json formate. After successfully validate form data then it will update data.

destroy() - For delete or remove mysql data, ajax request will be send to destroy() method. It will delete or remove mysql data in Laravel 5.8 by using ajax.


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\AjaxCrud;
use Validator;

class AjaxCrudController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        if(request()->ajax())
        {
            return datatables()->of(AjaxCrud::latest()->get())
                    ->addColumn('action', function($data){
                        $button = '<button type="button" name="edit" id="'.$data->id.'" class="edit btn btn-primary btn-sm">Edit</button>';
                        $button .= '&nbsp;&nbsp;';
                        $button .= '<button type="button" name="delete" id="'.$data->id.'" class="delete btn btn-danger btn-sm">Delete</button>';
                        return $button;
                    })
                    ->rawColumns(['action'])
                    ->make(true);
        }
        return view('ajax_index');
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $rules = array(
            'first_name'    =>  'required',
            'last_name'     =>  'required',
            'image'         =>  'required|image|max:2048'
        );

        $error = Validator::make($request->all(), $rules);

        if($error->fails())
        {
            return response()->json(['errors' => $error->errors()->all()]);
        }

        $image = $request->file('image');

        $new_name = rand() . '.' . $image->getClientOriginalExtension();

        $image->move(public_path('images'), $new_name);

        $form_data = array(
            'first_name'        =>  $request->first_name,
            'last_name'         =>  $request->last_name,
            'image'             =>  $new_name
        );

        AjaxCrud::create($form_data);

        return response()->json(['success' => 'Data Added successfully.']);
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        if(request()->ajax())
        {
            $data = AjaxCrud::findOrFail($id);
            return response()->json(['data' => $data]);
        }
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request)
    {
        $image_name = $request->hidden_image;
        $image = $request->file('image');
        if($image != '')
        {
            $rules = array(
                'first_name'    =>  'required',
                'last_name'     =>  'required',
                'image'         =>  'image|max:2048'
            );
            $error = Validator::make($request->all(), $rules);
            if($error->fails())
            {
                return response()->json(['errors' => $error->errors()->all()]);
            }

            $image_name = rand() . '.' . $image->getClientOriginalExtension();
            $image->move(public_path('images'), $image_name);
        }
        else
        {
            $rules = array(
                'first_name'    =>  'required',
                'last_name'     =>  'required'
            );

            $error = Validator::make($request->all(), $rules);

            if($error->fails())
            {
                return response()->json(['errors' => $error->errors()->all()]);
            }
        }

        $form_data = array(
            'first_name'       =>   $request->first_name,
            'last_name'        =>   $request->last_name,
            'image'            =>   $image_name
        );
        AjaxCrud::whereId($request->hidden_id)->update($form_data);

        return response()->json(['success' => 'Data is successfully updated']);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $data = AjaxCrud::findOrFail($id);
        $data->delete();
    }
}


Step 7 - Create Blades Files


For display output data in browser, in Laravel 5.8 we have to create blade file in resources/views folder. Under this folder we have create ajax_index.blade.php file. In this file you can find HTML code and jQuery code for display data in jQuery Datatable.


<html>
 <head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Laravel 5.8 - DataTables Server Side Processing using Ajax</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
  <script src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>  
  <link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
 </head>
 <body>
  <div class="container">    
     <br />
     <h3 align="center">Laravel 5.8 Ajax Crud Tutorial - Delete or Remove Data</h3>
     <br />
     <div align="right">
      <button type="button" name="create_record" id="create_record" class="btn btn-success btn-sm">Create Record</button>
     </div>
     <br />
   <div class="table-responsive">
    <table class="table table-bordered table-striped" id="user_table">
           <thead>
            <tr>
                <th width="10%">Image</th>
                <th width="35%">First Name</th>
                <th width="35%">Last Name</th>
                <th width="30%">Action</th>
            </tr>
           </thead>
       </table>
   </div>
   <br />
   <br />
  </div>
 </body>
</html>

<div id="formModal" class="modal fade" role="dialog">
 <div class="modal-dialog">
  <div class="modal-content">
   <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">&times;</button>
          <h4 class="modal-title">Add New Record</h4>
        </div>
        <div class="modal-body">
         <span id="form_result"></span>
         <form method="post" id="sample_form" class="form-horizontal" enctype="multipart/form-data">
          @csrf
          <div class="form-group">
            <label class="control-label col-md-4" >First Name : </label>
            <div class="col-md-8">
             <input type="text" name="first_name" id="first_name" class="form-control" />
            </div>
           </div>
           <div class="form-group">
            <label class="control-label col-md-4">Last Name : </label>
            <div class="col-md-8">
             <input type="text" name="last_name" id="last_name" class="form-control" />
            </div>
           </div>
           <div class="form-group">
            <label class="control-label col-md-4">Select Profile Image : </label>
            <div class="col-md-8">
             <input type="file" name="image" id="image" />
             <span id="store_image"></span>
            </div>
           </div>
           <br />
           <div class="form-group" align="center">
            <input type="hidden" name="action" id="action" />
            <input type="hidden" name="hidden_id" id="hidden_id" />
            <input type="submit" name="action_button" id="action_button" class="btn btn-warning" value="Add" />
           </div>
         </form>
        </div>
     </div>
    </div>
</div>

<div id="confirmModal" class="modal fade" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">&times;</button>
                <h2 class="modal-title">Confirmation</h2>
            </div>
            <div class="modal-body">
                <h4 align="center" style="margin:0;">Are you sure you want to remove this data?</h4>
            </div>
            <div class="modal-footer">
             <button type="button" name="ok_button" id="ok_button" class="btn btn-danger">OK</button>
                <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
            </div>
        </div>
    </div>
</div>


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

 $('#user_table').DataTable({
  processing: true,
  serverSide: true,
  ajax:{
   url: "{{ route('ajax-crud.index') }}",
  },
  columns:[
   {
    data: 'image',
    name: 'image',
    render: function(data, type, full, meta){
     return "<img src={{ URL::to('/') }}/images/" + data + " width='70' class='img-thumbnail' />";
    },
    orderable: false
   },
   {
    data: 'first_name',
    name: 'first_name'
   },
   {
    data: 'last_name',
    name: 'last_name'
   },
   {
    data: 'action',
    name: 'action',
    orderable: false
   }
  ]
 });

 $('#create_record').click(function(){
  $('.modal-title').text("Add New Record");
     $('#action_button').val("Add");
     $('#action').val("Add");
     $('#formModal').modal('show');
 });

 $('#sample_form').on('submit', function(event){
  event.preventDefault();
  if($('#action').val() == 'Add')
  {
   $.ajax({
    url:"{{ route('ajax-crud.store') }}",
    method:"POST",
    data: new FormData(this),
    contentType: false,
    cache:false,
    processData: false,
    dataType:"json",
    success:function(data)
    {
     var html = '';
     if(data.errors)
     {
      html = '<div class="alert alert-danger">';
      for(var count = 0; count < data.errors.length; count++)
      {
       html += '<p>' + data.errors[count] + '</p>';
      }
      html += '</div>';
     }
     if(data.success)
     {
      html = '<div class="alert alert-success">' + data.success + '</div>';
      $('#sample_form')[0].reset();
      $('#user_table').DataTable().ajax.reload();
     }
     $('#form_result').html(html);
    }
   })
  }

  if($('#action').val() == "Edit")
  {
   $.ajax({
    url:"{{ route('ajax-crud.update') }}",
    method:"POST",
    data:new FormData(this),
    contentType: false,
    cache: false,
    processData: false,
    dataType:"json",
    success:function(data)
    {
     var html = '';
     if(data.errors)
     {
      html = '<div class="alert alert-danger">';
      for(var count = 0; count < data.errors.length; count++)
      {
       html += '<p>' + data.errors[count] + '</p>';
      }
      html += '</div>';
     }
     if(data.success)
     {
      html = '<div class="alert alert-success">' + data.success + '</div>';
      $('#sample_form')[0].reset();
      $('#store_image').html('');
      $('#user_table').DataTable().ajax.reload();
     }
     $('#form_result').html(html);
    }
   });
  }
 });

 $(document).on('click', '.edit', function(){
  var id = $(this).attr('id');
  $('#form_result').html('');
  $.ajax({
   url:"/ajax-crud/"+id+"/edit",
   dataType:"json",
   success:function(html){
    $('#first_name').val(html.data.first_name);
    $('#last_name').val(html.data.last_name);
    $('#store_image').html("<img src={{ URL::to('/') }}/images/" + html.data.image + " width='70' class='img-thumbnail' />");
    $('#store_image').append("<input type='hidden' name='hidden_image' value='"+html.data.image+"' />");
    $('#hidden_id').val(html.data.id);
    $('.modal-title').text("Edit New Record");
    $('#action_button').val("Edit");
    $('#action').val("Edit");
    $('#formModal').modal('show');
   }
  })
 });

 var user_id;

 $(document).on('click', '.delete', function(){
  user_id = $(this).attr('id');
  $('#confirmModal').modal('show');
 });

 $('#ok_button').click(function(){
  $.ajax({
   url:"ajax-crud/destroy/"+user_id,
   beforeSend:function(){
    $('#ok_button').text('Deleting...');
   },
   success:function(data)
   {
    setTimeout(function(){
     $('#confirmModal').modal('hide');
     $('#user_table').DataTable().ajax.reload();
    }, 2000);
   }
  })
 });

});
</script>


Step 8 - Set Resource Route


Lastly, We need to set resource route for ajax crud application. For this we have to open routes/web.php file.


Route::resource('ajax-crud', 'AjaxCrudController');

Route::post('ajax-crud/update', 'AjaxCrudController@update')->name('ajax-crud.update');

Route::get('ajax-crud/destroy/{id}', 'AjaxCrudController@destroy');


For run Laravel 5.8 application, you can write following command.


php artisan serve


For see Laravel 5.8 application in your browser, you have to write following url.


http://localhost:8000/ajax-crud

Monday, 25 March 2019

Step by Step CRUD Operation in Laravel 5.8 with File Upload

Part 1 - Introduction




Part 2 - Fetch and Display Data




Part 3 - Insert or Add Data with File Upload



Part 4 - Fetch Single Data from Database



Part 5 - Edit or Update Existing MySQL Data



Part 6 - Delete data from Database




If you want to learn How can we do CRUD(Create, Read, Update, Delete) operation with upload file in new version of Laravel 5.8. So, from this post, you can find step by step process of doing CRUD with Mysql database from Laravel 5.8 application. For do CRUD in Laravel 5.8, first you have to upgrade your Laravel framework. For upgrade Laravel you have to go to this Laravel Upgrade Link. Contributors of Laravel has continue improvement in Laravel every version. So, in Laravel 5.8 version you can find something new as from Laravel 5.7. There are following new feature introduced in Laravel 5.8.

  • has-one-through Eloquent relationships.
  • Improved email validation.
  • convention-based automatic registration of authorization policies.
  • DynamoDB cache and session drivers.
  • Improved scheduler timezone configuration.
  • Support for assigning multiple authentication guards to broadcast channels.
  • PSR-16 cache driver compliance, improvements to the artisan serve command.
  • PHPUnit 8.0 support.
  • Carbon 2.0 support.
  • Pheanstalk 4.0 support, and a variety of other bug fixes and usability improvements.

If you want to get detailed information on Laravel 5.8, then you have go to this Laravel 5.8 relase Link.

Laravel 5.8 Server Requirements


If you want to use Laravel 5.8 for your web development, first you have to check what is minimum server requirement for using Laravel 5.8. Below you can find Laravel 5.8 server requirement.

  • PHP >= 7.1.3
  • OpenSSL PHP Extension
  • PDO PHP Extension
  • Mbstring PHP Extension
  • Tokenizer PHP Extension
  • XML PHP Extension
  • Ctype PHP Extension
  • JSON PHP Extension
  • BCMath PHP Extension

Suppose you have check all above server requirement, and you have all above requirement, then you can start using Laravel 5.8 framework version. So, here first we will make simple CRUD Application in Laravel 5.8, for this you have to following steps.


Step by Step CRUD Operation in Laravel 5.8 with File Upload


Step 1 - Download Laravel 5.8


In first step you have to download Laravel 5.8 version. For this you have to go to command prompt, in which first you have go to your folder path in which you want to download Laravel 5.8. After this you have to run "composer" command, because all Laravel depository handle by composer. After run "composer" command. You have to run following command.


composer create-project laravel/laravel=5.8 crud --prefer-dist


Above command will make crud folder and under this folder it will download Laravel 5.8.

Step 2 - Mysql Database connection Laravel 5.8


Once you have download Laravel 5.8, so now first we want to make Mysql database connection from Laravel 5.8. You can make Mysql database connection from two way.

In first way you have to find .env file in your Laravel 5.8 folder. Open that file and under you have to define your mysql database configuration like below.


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


In second way, you have to open config/database.php file, and under this file you can also define your mysql database configuration.


'mysql' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', '127.0.0.1'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'testing'),
            'username' => env('DB_USERNAME', 'root'),
            'password' => env('DB_PASSWORD', ''),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'prefix_indexes' => true,
            'strict' => true,
            'engine' => null,
            'options' => array_filter([
                PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
            ]),
        ],


After defining above details you can make Mysql database connection from your Laravel 5.8 application.

Step 3 - Migrate Table from Laravel 5.8 to Mysql Database


In Laravel framework, you have facility from make table in Mysql database from your Laravel application. For this first you have to create migration file in your Laravel folder. For this you have to write following command in your command prompt.


php artisan make:migration create_crud_table --create=crud


This command will create migration file in database/migrations folder. In this file we have to define table column which we want to create in table. Below you can find migration file in which we have define table column.


<?php

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

class CreateCrudTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('cruds', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('first_name');
            $table->string('last_name');
            $table->string('image');
            $table->timestamps();
        });
    }

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


Now we want to migrate this table definition from this Laravel application to mysql database. For this we have write following command in command prompt. This command will make crud table in mysql database for perform CRUD operation from Laravel 5.8 application.


php artisan migrate


Step 4 - Create Model file in Laravel 5.8


In this we will seen how can we make model file in Laravel 5.8. This class file mainly used for do database related operation in controller class. For create model files we have to write following command in command prompt.


php artisan make:model Crud -m


This command will make Crud.php model file in app folder. In this file we have to define table column name which you can see below source code of Crud.php file.


<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Crud extends Model
{
    protected $fillable = [
     'first_name', 'last_name', 'image'
    ];
}





Step 5 - Create Controllers in Laravel 5.8


Controllers files mainly used for handle http request in Laravel 5.8 application. Here we want to create Laravel 5.8 crud controller. For this we have to go to command prompt and under this we have write following command.


php artisan make:controller CrudsController --resource


This command will make CrudsController.php file in app/Http/Controllers folder. Once you have open this file, then you can find all predefine method for do CRUD operation in this controller file. We have to just add code for do particular operation. Below you can find CRUD controller file code below.


<?php

namespace App\Http\Controllers;
use App\Crud;
use Illuminate\Http\Request;

class CrudsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $data = Crud::latest()->paginate(5);
        return view('index', compact('data'))
                ->with('i', (request()->input('page', 1) - 1) * 5);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('create');
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request->validate([
            'first_name'    =>  'required',
            'last_name'     =>  'required',
            'image'         =>  'required|image|max:2048'
        ]);

        $image = $request->file('image');

        $new_name = rand() . '.' . $image->getClientOriginalExtension();
        $image->move(public_path('images'), $new_name);
        $form_data = array(
            'first_name'       =>   $request->first_name,
            'last_name'        =>   $request->last_name,
            'image'            =>   $new_name
        );

        Crud::create($form_data);

        return redirect('crud')->with('success', 'Data Added successfully.');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $data = Crud::findOrFail($id);
        return view('view', compact('data'));
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        $data = Crud::findOrFail($id);
        return view('edit', compact('data'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $image_name = $request->hidden_image;
        $image = $request->file('image');
        if($image != '')
        {
            $request->validate([
                'first_name'    =>  'required',
                'last_name'     =>  'required',
                'image'         =>  'image|max:2048'
            ]);

            $image_name = rand() . '.' . $image->getClientOriginalExtension();
            $image->move(public_path('images'), $image_name);
        }
        else
        {
            $request->validate([
                'first_name'    =>  'required',
                'last_name'     =>  'required'
            ]);
        }

        $form_data = array(
            'first_name'       =>   $request->first_name,
            'last_name'        =>   $request->last_name,
            'image'            =>   $image_name
        );
  
        Crud::whereId($id)->update($form_data);

        return redirect('crud')->with('success', 'Data is successfully updated');
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        $data = Crud::findOrFail($id);
        $data->delete();

        return redirect('crud')->with('success', 'Data is successfully deleted');
    }
}


index() - In Laravel Crud controller index() method is a root method of crud controller, so when in browser we have enter base url with controller name, then it will called this index() method. Under this method we will write code for display data from mysql database. In this code it will first fetch data from crud table and store under $data variable, after this we want to make paginate link by using paginate() method in Laravel 5.8. For send data to view file, for this we have use view() method for send data to view file. Source code you can find under index() method.

create() - This method has been used for load create.blade.php file. In this file user can find form for insert new records and filling data insert data request will be send to store() method of CrudsController.php controller class.

store() - This method has received add or insert new records request received from create() method. In this method, it will perform two operation. One is for upload image file by using move() method and second is for insert records into mysql table by using model class. Before upload of image, it will rename image name. After successfully insert or add of data in mysql table from this Laravel 5.8 application, page will redirect to index() method with success message.

show() - This method in Crud controller has been used for fetch single data details based on on value of $id argument. For this it has been used findOrFail() method. After fetch details it will send to view.blade.php file.

edit() - This method main function is fetch single data from Mysql database and load into edit or update form for make required changes.

update() - Update method has received edit or update data request from edit(). This method has done two function like upload of profile image with update or edit mysql data in Laravel 5.8 framework.

delete() - Delete() method mainly used for remove single or multiple data from Mysql Database. This is last operation Crud Operation in Laravel 5.8 Crud tutorial series.




Step 6 - Set Route in Laravel 5.8


This is very useful step in Laravel 5.8, because here we want to set route of all CrudsController class method. For this we have to open to routes/web.php file. In this file we have to write following code for set route of all method.


Route::resource('crud','CrudsController');


Step 7 - Set Data in View File in Laravel 5.8


This is the last step in Laravel 5.8 Crud application, and in this step we have to set data in view file which has been store under resources/views folder, because this view file has received data from controller method, so here we have to set data in view file. Below you can file all view file which has been used in Crud application, and you can also find how data has been set and how to make form in Laravel 5.8 view file.

resources/views/parent.blade.php

<html>
 <head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Laravel 5.8 Crud Tutorial</title>
  <meta content='width=device-width, initial-scale=1, maximum-scale=1' name='viewport'/>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
 </head>
 <body>
  <div class="container">    
     <br />
     <h3 align="center">Laravel 5.8 Crud Tutorial</h3>
     <br />
     @yield('main')
    </div>
 </body>
</html>


resources/views/index.blade.php

@extends('parent')

@section('main')

<table class="table table-bordered table-striped">
 <tr>
  <th width="10%">Image</th>
  <th width="35%">First Name</th>
  <th width="35%">Last Name</th>
  <th width="30%">Action</th>
 </tr>
 @foreach($data as $row)
  <tr>
   <td><img src="{{ URL::to('/') }}/images/{{ $row->image }}" class="img-thumbnail" width="75" /></td>
   <td>{{ $row->first_name }}</td>
   <td>{{ $row->last_name }}</td>
   <td>
    
   </td>
  </tr>
 @endforeach
</table>
{!! $data->links() !!}
@endsection


resources/views/create.blade.php

@extends('parent')

@section('main')
@if($errors->any())
<div class="alert alert-danger">
 <ul>
  @foreach($errors->all() as $error)
  <li>{{ $error }}</li>
  @endforeach
 </ul>
</div>
@endif
<div align="right">
 <a href="{{ route('crud.index') }}" class="btn btn-default">Back</a>
</div>

<form method="post" action="{{ route('crud.store') }}" enctype="multipart/form-data">

 @csrf
 <div class="form-group">
  <label class="col-md-4 text-right">Enter First Name</label>
  <div class="col-md-8">
   <input type="text" name="first_name" class="form-control input-lg" />
  </div>
 </div>
 <br />
 <br />
 <br />
 <div class="form-group">
  <label class="col-md-4 text-right">Enter Last Name</label>
  <div class="col-md-8">
   <input type="text" name="last_name" class="form-control input-lg" />
  </div>
 </div>
 <br />
 <br />
 <br />
 <div class="form-group">
  <label class="col-md-4 text-right">Select Profile Image</label>
  <div class="col-md-8">
   <input type="file" name="image" />
  </div>
 </div>
 <br /><br /><br />
 <div class="form-group text-center">
  <input type="submit" name="add" class="btn btn-primary input-lg" value="Add" />
 </div>

</form>

@endsection


resources/views/view.blade.php

@extends('parent')

@section('main')

<div class="jumbotron text-center">
 <div align="right">
  <a href="{{ route('crud.index') }}" class="btn btn-default">Back</a>
 </div>
 <br />
 <img src="{{ URL::to('/') }}/images/{{ $data->image }}" class="img-thumbnail" />
 <h3>First Name - {{ $data->first_name }} </h3>
 <h3>Last Name - {{ $data->last_name }}</h3>
</div>
@endsection


resources/views/edit.blade.php

@extends('parent')

@section('main')
            
            @if ($errors->any())
                <div class="alert alert-danger">
                    <ul>
                        @foreach ($errors->all() as $error)
                            <li>{{ $error }}</li>
                        @endforeach
                    </ul>
                </div>
            @endif
            <div align="right">
                <a href="{{ route('crud.index') }}" class="btn btn-default">Back</a>
            </div>
            <br />
     <form method="post" action="{{ route('crud.update', $data->id) }}" enctype="multipart/form-data">
                @csrf
                @method('PATCH')
      <div class="form-group">
       <label class="col-md-4 text-right">Enter First Name</label>
       <div class="col-md-8">
        <input type="text" name="first_name" value="{{ $data->first_name }}" class="form-control input-lg" />
       </div>
      </div>
      <br />
      <br />
      <br />
      <div class="form-group">
       <label class="col-md-4 text-right">Enter Last Name</label>
       <div class="col-md-8">
        <input type="text" name="last_name" value="{{ $data->last_name }}" class="form-control input-lg" />
       </div>
      </div>
      <br />
      <br />
      <br />
      <div class="form-group">
       <label class="col-md-4 text-right">Select Profile Image</label>
       <div class="col-md-8">
        <input type="file" name="image" />
              <img src="{{ URL::to('/') }}/images/{{ $data->image }}" class="img-thumbnail" width="100" />
                        <input type="hidden" name="hidden_image" value="{{ $data->image }}" />
       </div>
      </div>
      <br /><br /><br />
      <div class="form-group text-center">
       <input type="submit" name="edit" class="btn btn-primary input-lg" value="Edit" />
      </div>
     </form>

@endsection


Step 8 - Run Laravel 5.8 Application


Lastly, we want to run Laravel 5.8 Crud application, for this we have to go to command prompt, and write following command.


php artisan serve


Above command will start Laravel 5.8 application. For run Larave 5.8 crud file, you have to write this url http://127.0.0.1:8000/crud in your browser for test code is working or not.

Here will make simple CRUD application with uploading file in Laravel 5.8 version.





Thursday, 14 March 2019

Creating Valid RSS feed in PHP



RSS Feature in content based website has been used by number of website owner around the world for get information of latest content information from online website.

RSS is a very simple broadcast feature which is used from introduce updated information to number of receivers.

RSS will automatically send changed content regularly to the user.

If you seen orange icon on many website, that means that website has provide content through RSS feed.

So, in this post we will make dynamic RSS feed by using PHP script from data has been fetch from Mysql database. In this post you can find out how to create your own custom RSS by using PHP script and Mysql. Before we will discuss which tag has been used to make RSS feed and what is use of that tag in RSS feed and lastly we will seen how to use PHP script for implementing dynamic RSS feed in PHP.

RSS feed must add following fields.

<?xml ?> - RSS feed must be start with this XML tag in which we have to define version of XML.

<rss> - Below XML tag we have start define RSS feed by using this tag, in which we can define version of RSS.

<channel> - In RSS feed first we have to create channel by using this tag.

<title> - RSS feed name has been define under this <title> tag.

<link> - RSS feed link has been define in <link> tag.

<description> - A short description of RSS feed must be set under this <description> tag.

<language> - We must have to define RSS feed language, which has been define under tag. For example, American English language RSS feed we have to write "en-us", here en is ISO-639 language code and us stand for ISO-3166 country codes.

All above tag has been in RSS feed header section, but all below tag will be used in body section of RSS feed which is under each item comes in the feed.

<item> - RSS feed item has been define by this tag.

<title> - RSS feed item title has been set under this tag.

<link> - Link of each item has been define under this <link> tag.

<description> - Under this tag we can define short description of each item, and description must contain at least 300 or more characters.

<pubDate> - Publication date of each item has been define under this <pubDate> tag and date must be ISO 8601 or RFC822 standard format.

<guid> - In RSS feed, we have to provide unique id for each item, which has been define under this <guid> tag.

<dc:creator>
- Name of the author has been define under this tag.
<enclosure> - Any media attachment like image or video link has been define under this tag, here we have also define size of attachment with it's mime type also.

Optional: <category> - This is optional tag in RSS feed and here we can define category of each item.

This is complete description of RSS feed tag, below you can find source code of How to create dynamic RSS feed in PHP with Mysql database.






Mysql Table



--
-- Table structure for table `tbl_post`
--

CREATE TABLE `tbl_post` (
  `id` mediumint(8) UNSIGNED NOT NULL,
  `post_title` text,
  `post_description` text,
  `author` varchar(255) DEFAULT NULL,
  `datetime` datetime DEFAULT NULL,
  `post_image` varchar(150) DEFAULT NULL,
  `post_url` varchar(150) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

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

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `tbl_post`
--
ALTER TABLE `tbl_post`
  MODIFY `id` mediumint(8) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;



index.php



<?php

//index.php

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

$query = "SELECT * FROM tbl_post ORDER BY id DESC";

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

$statement->execute();

$result = $statement->fetchAll();

header("Content-Type: text/xml;charset=iso-8859-1");

$base_url = "http://localhost/tutorial/how-to-create-dynamic-rss-feed-in-php/";

echo "<?xml version='1.0' encoding='UTF-8' ?>" . PHP_EOL;
echo "<rss version='2.0'>".PHP_EOL;
echo "<channel>".PHP_EOL;
echo "<title>Feed Title | RSS</title>".PHP_EOL;
echo "<link>".$base_url."index.php</link>".PHP_EOL;
echo "<description>Cloud RSS</description>".PHP_EOL;
echo "<language>en-us</language>".PHP_EOL;

foreach($result as $row)
{
 $publish_Date = date("D, d M Y H:i:s T", strtotime($row["datetime"]));
 $image_size_array = get_headers($base_url . "images/".$row["post_image"], 1);
 $image_size = $image_size_array["Content-Length"];
 $image_mime_array = getimagesize($base_url . "images/".$row["post_image"]);
 $image_mime = $image_mime_array["mime"];
 
 echo "<item xmlns:dc='ns:1'>".PHP_EOL;
 echo "<title>".$row["post_title"]."</title>".PHP_EOL;
 echo "<link>".$base_url."blog/".$row["post_url"]."/</link>".PHP_EOL;
 echo "<guid>".md5($row["id"])."</guid>".PHP_EOL;
 echo "<pubDate>".$publish_Date."</pubDate>".PHP_EOL;
 echo "<dc:creator>".$row["author"]."</dc:creator>".PHP_EOL;
 echo "<description><![CDATA[".substr($row["post_description"], 0, 300) ."]]></description>".PHP_EOL;
 echo "<enclosure url='images/".$row["post_image"]."' length='".$image_size."' type='".$image_mime."' />".PHP_EOL;
 echo "<category>PHP tutorial</category>".PHP_EOL;
 echo "</item>".PHP_EOL;
}

echo '</channel>'.PHP_EOL;
echo '</rss>'.PHP_EOL;

?>


Reading RSS Feed with PHP



Above we have seen how to build RSS Feed using Dynamic Mysql data in PHP. Here you can find Reading of XML RSS Feed data using PHP script. There are many website which has use XML RSS feed for received data from other site for display on their website. There is one benifits of using XML RSS feed data is that content receiver site has not store other website data on their website, and benifits to content website owner is that he can publish their website content on other website by add content into RSS feed.

So, there benifits to both content publisher and content provider. This is main benifits of RSS feed. Below you can find complete PHP Source code of reading of RSS feed in PHP.


<?php

//read.php

$feed_url = "http://localhost/tutorial/how-to-create-dynamic-rss-feed-in-php/index.php";

$object = new DOMDocument();

$object->load($feed_url);

$content = $object->getElementsByTagName("item");


?>

<!DOCTYPE html>
<html>
 <head>
  <title>How to Read RSS Feed in PHP</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
 </head>
 <body>
  <div class="container">
   <br />
   <h2 align="center">How to Read RSS Feed in PHP</h2>
   <br />
   <?php
    
   foreach($content as $row)
   {
    echo '<h3 class="text-info">' . $row->getElementsByTagName("title")->item(0)->nodeValue . '</h3>';
    echo '<hr />';
    echo '
    <div class="row">
     <div class="col-md-3">
      <p>'.$row->getElementsByTagName("pubDate")->item(0)->nodeValue.'</p>
      <br />
      <img src="'.$row->getElementsByTagName("enclosure")->item(0)->attributes["url"]->nodeValue.'" class="img-responsive img-thumbnail" />
     </div>
     <div class="col-md-9">
      <p align="right"><b><i>By '.$row->getElementsByTagNameNS("ns:1", "*")->item(0)->nodeValue.'</i></b></p>
      <br />
      <p>'.$row->getElementsByTagName("description")->item(0)->nodeValue.'</p>
     </div>
    </div>
    ';
    echo '<br />';
    echo '<span class="label label-primary">'.$row->getElementsByTagName("category")->item(0)->nodeValue.'</span>';
    echo '<br />';
    echo '<hr />';
    echo '<br />';
    
   }

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

Tuesday, 12 March 2019

Ajax jQuery Based Star Rating System in Codeigniter



In this post, We will learn to make 5 Star Rating System in Codeigniter by using Ajax jQuery and Mysql database. Five Star Rating will allows to user to submit their review on any product or service or business unit is useful or not. User can send Live Rating on product and on web page it will get live result of result on web page without refresh of web page. Because here we will use Ajax with Codeigniter framework for developing Star Rating application. This feature is very common in most of the e-commerce who want to sale their product online. Based on rating user can get idea which product is good based on multiple user review.

In this system User can rate the business unit or product based on their quality of product or services, advantages of product etc. So, that rating will helpful to other user who want to use particular business unit service or buy product then based on other user review or rating new user will idea regarding of listed product on e-commerce site.

In this tutorial, we will use pure jquery and Ajax code for make Star rating in Codeigniter, here we have not use any jQuery plugin for implement star rating system in Codeigniter. This is dynamic star rating system, in which rating will be display on average rating of all user, which we have been make in Codeigniter using Ajax jQuery. In this system when use click on particular number of Star then Ajax request has been send to Codeigniter controller, which will insert rating data of particular product in Mysql table. This is simple Codeigniter Ajax based Star rating system script which will help you to developed 5 star rating feature in your Codeigniter web application. Below you can find complete step by step process of How to build Star rating in Codeigniter using Ajax jquery and Mysql.






Step 1 - Create Table


First, We have to create table in Mysql database, in this we have to make business and rating. This two table we will for build dynamic star rating system.


--
-- Database: `testing`
--

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

--
-- Table structure for table `business`
--

CREATE TABLE `business` (
  `id` int(11) NOT NULL,
  `business_name` varchar(300) NOT NULL,
  `address` text NOT NULL,
  `product` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `business`
--

INSERT INTO `business` (`id`, `business_name`, `address`, `product`) VALUES
(1, 'Fog Harbor Fish House', 'Fisherman\'s Wharf, North Beach/Telegraph Hill\r\nPier 39\r\nSan Francisco, CA 94133\r\nPhone number (415) 421-2442', 'Seafood, Bars'),
(2, 'The House', 'North Beach/Telegraph Hill\r\n1230 Grant Ave\r\nSan Francisco, CA 94133\r\nPhone number (415) 986-8612', 'Asian Fusion'),
(3, 'Barnzu', 'Tenderloin\r\n711 Geary St\r\nSan Francisco, CA 94109\r\nPhone number (415) 525-4985', 'Korean, Tapas Bars'),
(4, 'Brenda French Soul Food', 'Tenderloin\r\n652 Polk St\r\nSan Francisco, CA 94102\r\nPhone number (415) 345-8100', 'Breakfast & Brunch, French, Soul Food'),
(5, 'The Salzburg', 'Russian Hill, North Beach/Telegraph Hill\r\n663 Union St\r\nSan Francisco, CA 94133', 'Austrian'),
(6, 'Marufuku Ramen', 'Lower Pacific Heights, Japantown\r\n1581 Webster St\r\nSan Francisco, CA 94115\r\nPhone number (415) 872-9786', 'Seafood, Seafood Markets, Live/Raw Food');

--
-- Indexes for dumped tables
--

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

--
-- AUTO_INCREMENT for dumped tables
--

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

--
-- Table structure for table `rating`
--

CREATE TABLE `rating` (
  `rating_id` int(11) NOT NULL,
  `business_id` int(11) NOT NULL,
  `rating` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `rating`
--

INSERT INTO `rating` (`rating_id`, `business_id`, `rating`) VALUES
(1, 6, 3),
(2, 6, 5),
(3, 6, 3),
(4, 5, 3),
(5, 5, 2),
(6, 5, 5),
(7, 5, 5),
(8, 5, 5),
(9, 5, 1),
(10, 3, 5),
(11, 4, 3),
(12, 4, 5),
(13, 4, 3),
(14, 4, 5),
(15, 1, 3),
(16, 1, 1),
(17, 1, 2),
(18, 1, 5),
(19, 1, 5),
(20, 2, 4);

--
-- Indexes for dumped tables
--

--
-- Indexes for table `rating`
--
ALTER TABLE `rating`
  ADD PRIMARY KEY (`rating_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `rating`
--
ALTER TABLE `rating`
  MODIFY `rating_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=21;


Step 2 - Database Connection


In second step, we have to make database connection in Codeigniter framework, for this we have to go to application/config/database.php and in this file we have to define Mysql database configuration details.


<?php

$active_group = 'default';
$query_builder = TRUE;

$db['default'] = array(
 'dsn' => '',
 'hostname' => 'localhost',
 'username' => 'root',
 'password' => '',
 'database' => 'testing',
 'dbdriver' => 'mysqli',
 'dbprefix' => '',
 'pconnect' => FALSE,
 'db_debug' => (ENVIRONMENT !== 'production'),
 'cache_on' => FALSE,
 'cachedir' => '',
 'char_set' => 'utf8',
 'dbcollat' => 'utf8_general_ci',
 'swap_pre' => '',
 'encrypt' => FALSE,
 'compress' => FALSE,
 'stricton' => FALSE,
 'failover' => array(),
 'save_queries' => TRUE
);


?>


Step 3 - Controllers (Star_rating.php)


After this we have to make Star_rating.php controller file under application/controllers folder. In this class we have create following method for handle HTTP request.

__construnct() - This magic method will execute this block of code on every time when object of this class has been created.

index() - This is the root method of this Controllers class, when in browser we have enter base_url/star_rating, then it will execute this method which will load application/views/star_raing.php file as an output in browser.

fetch() - This method will display all business unit data on web page with Star rating. This method has received Ajax request for display all product details with star rating on web page.

insert() - This method will insert rating data by using models method. This method also received Ajax request for insert user rating data into Mysql table.


<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Star_rating extends CI_Controller {

 public function __construct()
 {
  parent::__construct();
  $this->load->model('star_rating_model');
 }

 function index()
 {
  $this->load->view('star_rating');
 }

 function fetch()
 {
  echo $this->star_rating_model->html_output();
 }

 function insert()
 {
  if($this->input->post('business_id'))
  {
   $data = array(
    'business_id'  => $this->input->post('business_id'),
    'rating'   => $this->input->post('index')
   );
   $this->star_rating_model->insert_rating($data);
  }
 }

}
?>


Step 4 - Models (Star_rating_model.php)


In Codeigniter framework, models class has been mainly used for do all Mysql database operation. This class method will be execute from controller class method. In this class we have use following make following method for star rating system.

get_business_data() - This method will return all business table data.

get_business_rating($business_id) - This method will return average rating of business based on $business_id argument.

html_output() - This method will convert all business data with rating in html format, this method has been called fetch method of Star_rating controllers class.

insert_rating() - This method will insert user rating data into rating Mysql table. This method has been called from insert() method of Star_rating controller.


<?php
class Star_rating_model extends CI_Model
{
 function get_business_data()
 {
  $this->db->order_by('id', 'DESC');
  return $this->db->get('business');
 }

 function get_business_rating($business_id)
 {
  $this->db->select('AVG(rating) as rating');
  $this->db->from('rating');
  $this->db->where('business_id', $business_id);
  $data = $this->db->get();
  foreach($data->result_array() as $row)
  {
   return $row["rating"];
  }
 }

 function html_output()
 {
  $data = $this->get_business_data();
  $output = '';
  foreach($data->result_array() as $row)
  {
   $color = '';
   $rating = $this->get_business_rating($row["id"]);
   $output .= '
   <h3 class="text-primary">'.$row["business_name"].'</h3>
   <ul class="list-inline" data-rating="'.$rating.'" title="Average Rating - '.$rating.'">
   ';
   for($count = 1; $count <= 5; $count++)
   {
    if($count <= $rating)
    {
     $color = 'color:#ffcc00;';
    }
    else
    {
     $color = 'color:#ccc;';
    }

    $output .= '<li title="'.$count.'" id="'.$row['id'].'-'.$count.'" data-index="'.$count.'" data-business_id="'.$row["id"].'" data-rating="'.$rating.'" class="rating" style="cursor:pointer; '.$color.' font-size:24px;">&#9733;</li>';
   }
   $output .= '</ul>
   <p>'.$row["address"].'</p>
   <label style="text-danger">'.$row["product"].'</label>
   <hr />
   ';
  }
  echo $output;
 }

 function insert_rating($data)
 {
  $this->db->insert('rating', $data);
 }
}

?>




Step 5 - Views (star_rating.php)


In Codeigniter framework views file has been used for display HTML output on web page. In this file we have use jQuery function for load business data on web page. In jQuery function, it has use Ajax request for display business and rating data on web page. Same way for insert rating data, here also we have use Ajax. So, all operation will be perform without refresh of web page. For star rating effect we have use jQuery code. This all source code you can find below.


<html>
<head>
    <title>Star Rating in Codeigniter using Ajax jQuery</title>
    
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
 <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    
</head>
<body>
 <div class="container box">
  <h3 align="center">Star Rating in Codeigniter using Ajax jQuery</h3>
  <br />
  <span id="business_list"></span>
 </div>
</body>
</html>

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

 load_data();

 function load_data()
 {
  $.ajax({
   url:"<?php echo base_url(); ?>star_rating/fetch",
   method:"POST",
   success:function(data)
   {
    $('#business_list').html(data);
   }
  })
 }

 $(document).on('mouseenter', '.rating', function(){
  var index = $(this).data('index');
  var business_id = $(this).data('business_id');
  remove_background(business_id);
  for(var count = 1; count <= index; count++)
  {
   $('#'+business_id+'-'+count).css('color', '#ffcc00');
  }
 });

 function remove_background(business_id)
 {
  for(var count = 1; count <= 5; count++)
  {
   $('#'+business_id+'-'+count).css('color', '#ccc');
  }
 }

 $(document).on('click', '.rating', function(){
  var index = $(this).data('index');
  var business_id = $(this).data('business_id');
  $.ajax({
   url:"<?php echo base_url(); ?>star_rating/insert",
   method:"POST",
   data:{index:index, business_id:business_id},
   success:function(data)
   {
    load_data();
    alert("You have rate "+index +" out of 5");
   }
  })
 });

 $(document).on('mouseleave', '.rating', function(){
  var index = $(this).data('index');
  var business_id = $(this).data('business_id');
  var rating = $(this).data('rating');
  remove_background(business_id);
  for(var count = 1; count <= rating; count++)
  {
   $('#'+business_id+'-'+count).css('color', '#ffcc00');
  }
 });

});
</script>


This is the complete step by step process for create Star rating system in Codeigniter using Ajax jquery. So, you can learn something new in Codeigniter framework. If you want to see demo this post, you can find below demo link.