Showing posts with label laravel 5.8 tutorial. Show all posts
Showing posts with label laravel 5.8 tutorial. Show all posts

Friday, 19 July 2019

Implement Custom Search Filter in Laravel 5.8 Datatable using Ajax



If you are using Laravel framework and you are using Datatable for display data on web page in tabular format. This is because Laravel Datatable has provide lots of feature like searching, paginate data, column sorting etc. without write any line of code. But some time this Datatable default search feature is not satisfy our data searching needs. e.g. Suppose we want to get male gender data, then we have enter male in search textbox, then at that time it will load female data also, this is because "male" word has been also come in "female" word also. So at that time we want to make custom search filter in Laravel datatable for filter exact particular word data only.

For this things here we have make custom search filter in Laravel 5.8 Datatable by using Ajax. In Laravel 5.8 framework, for use Datatable in Laravel 5.8 application we have use yajra Laravel datatable package. By using this yajra Laravel Datatable package we can implement Datatable in Laravel 5.8 application. Here we will show you how to add custom search filter with yajra datatables in Laravel 5.8 framework. Suppose we want to add custom search filter like dropdown or specific fields of database then also you can do it by using Laravel 5.8 Datatable.

We all now Laravel yajra Datatable has provide by default global search feature, and in that search feature it has search entire row of table. But if we want to required search filter for only one specific table column with select box then we should have to implement custom search filter of data in our Datatable. Below you can find step by step process for how to make custom search filter in Laravel 5.8 Datatable by using yajra datatables package and Ajax jquery.

  • Install Laravel 5.8 framework

  • Make Database connection Laravel Framework

  • Install yajra datatables package

  • Create Controller

  • Create View Blade file

  • Set Route

  • Run Laravel Application



Install Laravel 5.8 framework


First we need to download and install Laravel 5.8 framework. So we have to go command prompt, in which we have to first run composer command and then after we have to define folder in which we want to download and install Laravel 5.8 framework, and lastly we have to write following command. This command will download latest Laravel framework in define folder.


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


Make Database connection Laravel Framework


Once Laravel 5.8 framework download and install, then after we have to make database connection. For make database connection in Laravel 5.8 framework. For this we have to open .env file and in this file we need to define mysql configuration details, which you can see below.


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


tbl_customer.sql



--
-- Database: `testing`
--

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

--
-- Table structure for table `tbl_customer`
--

CREATE TABLE `tbl_customer` (
  `CustomerID` int(11) NOT NULL,
  `CustomerName` varchar(250) NOT NULL,
  `Gender` varchar(30) NOT NULL,
  `Address` text NOT NULL,
  `City` varchar(250) NOT NULL,
  `PostalCode` varchar(30) NOT NULL,
  `Country` varchar(100) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

--
-- Dumping data for table `tbl_customer`
--

INSERT INTO `tbl_customer` (`CustomerID`, `CustomerName`, `Gender`, `Address`, `City`, `PostalCode`, `Country`) VALUES
(1, 'Maria Anders', 'Female', 'Obere Str. 57', 'Berlin', '12209', 'Germany'),
(2, 'Ana Trujillo', 'Female', 'Avda. de la Construction 2222', 'Mexico D.F.', '5021', 'Mexico'),
(3, 'Antonio Moreno', 'Male', 'Mataderos 2312', 'Mexico D.F.', '5023', 'Mexico'),
(4, 'Thomas Hardy', 'Male', '120 Hanover Sq.', 'London', 'WA1 1DP', 'United Kingdom'),
(5, 'Paula Parente', 'Female', 'Rua do Mercado, 12', 'Resende', '08737-363', 'Brazil'),
(6, 'Wolski Zbyszek', 'Male', 'ul. Filtrowa 68', 'Walla', '01-012', 'Poland'),
(7, 'Matti Karttunen', 'Male', 'Keskuskatu 45', 'Helsinki', '21240', 'Finland'),
(8, 'Karl Jablonski', 'Male', '305 - 14th Ave. S. Suite 3B', 'Seattle', '98128', 'United States'),
(9, 'Paula Parente', 'Female', 'Rua do Mercado, 12', 'Resende', '08737-363', 'Brazil'),
(10, 'John Koskitalo', 'Male', 'Torikatu 38', 'Oulu', '90110', 'Finland'),
(39, 'Ann Devon', 'Female', '35 King George', 'London', 'WX3 6FW', 'United Kingdom'),
(38, 'Janine Labrune', 'Female', '67, rue des Cinquante Otages', 'Nantes', '44000', 'Finland'),
(37, 'Kathryn Segal', 'Female', 'Augsburger Strabe 40', 'Ludenscheid Gevelndorf', '58513', 'Germany'),
(36, 'Elizabeth Brown', 'Female', 'Berkeley Gardens 12 Brewery', 'London', 'WX1 6LT', 'United Kingdom'),
(30, 'Trina Davidson', 'Female', '1049 Lockhart Drive', 'Barrie', 'ON L4M 3B1', 'Canada'),
(31, 'Jeff Putnam', 'Male', 'Industrieweg 56', 'Bouvignies', '7803', 'Belgium'),
(32, 'Joyce Rosenberry', 'Female', 'Norra Esplanaden 56', 'HELSINKI', '380', 'Finland'),
(33, 'Ronald Bowne', 'Male', '2343 Shadowmar Drive', 'New Orleans', '70112', 'United States'),
(34, 'Justin Adams', 'Male', '45, rue de Lille', 'ARMENTIERES', '59280', 'France'),
(35, 'Pedro Afonso', 'Male', 'Av. dos Lusiadas, 23', 'Sao Paulo', '05432-043', 'Brazil'),
(100, 'Kathryn Segal', 'Female', 'Augsburger Strabe 40', 'Ludenscheid Gevelndorf', '58513', 'Germany'),
(101, 'Tonia Sayre', 'Female', '84 Haslemere Road', 'ECHT', 'AB32 2DY', 'United Kingdom'),
(102, 'Loretta Harris', 'Female', 'Avenida Boavista 71', 'SANTO AMARO', '4920-111', 'Portugal'),
(103, 'Sean Wong', 'Male', 'Rua Vito Bovino, 240', 'Sao Paulo-SP', '04677-002', 'Brazil'),
(104, 'Frederick Sears', 'Male', 'ul. Marysiuska 64', 'Warszawa', '04-617', 'Poland'),
(105, 'Tammy Cantrell', 'Female', 'Lukiokatu 34', 'HAMEENLINNA', '13250', 'Finland'),
(106, 'Megan Kennedy', 'Female', '1210 Post Farm Road', 'Norcross', '30071', 'United States'),
(107, 'Maria Whittaker', 'Female', 'Spresstrasse 62', 'Bielefeld Milse', '33729', 'Germany'),
(108, 'Dorothy Parker', 'Female', '32 Lairg Road', 'NEWCHURCH', 'HR5 5DR', 'United Kingdom'),
(109, 'Roger Rudolph', 'Male', 'Avenida Julio Saul Dias 78', 'PENAFIEL', '4560-470', 'Portugal'),
(110, 'Karen Metivier', 'Female', 'Rua Guimaraes Passos, 556', 'Sao Luis-MA', '65025-450', 'Brazil'),
(111, 'Charles Hoover', 'Male', 'Al. Tysiaclecia 98', 'Warszawa', '03-851', 'Poland'),
(112, 'Becky Moss', 'Female', 'Laivurinkatu 6', 'MIKKELI', '50120', 'Finland'),
(113, 'Frank Kidd', 'Male', '2491 Carson Street', 'Cincinnati', 'KY 45202', 'United States'),
(114, 'Donna Wilson', 'Female', 'Hallesches Ufer 69', 'Dettingen', '73265', 'Germany'),
(115, 'Lillian Roberson', 'Female', '36 Iolaire Road', 'NEW BARN', 'DA3 3FT', 'United Kingdom'),
(144, 'Stephen M. Menzies', 'Male', '577 Hartway Street', 'Bruie', '57325', 'United States'),
(143, 'Nikki G. Pascual', 'Female', '4291 Kinney Street', 'Agawam', '1001', 'United States'),
(141, 'Alpha A. Brookover', 'Female', '3542 Trainer Avenue', 'Kilbourne', '62655', 'United States'),
(142, 'Austin D. Salem', 'Male', '1184 Farland Street', 'Brockton', '2401', 'United States'),
(140, 'Bianca A. Carone', 'Female', '1777 Elkview Drive', 'Hialeah', '33012', 'United States'),
(139, 'Stephen M. Menzies', 'Male', '577 Hartway Street', 'Bruie', '57325', 'United States'),
(138, 'Nikki G. Pascual', 'Female', '4291 Kinney Street', 'Agawam', '1001', 'United States'),
(136, 'Alpha A. Brookover', 'Female', '3542 Trainer Avenue', 'Kilbourne', '62655', 'United States'),
(137, 'Austin D. Salem', 'Male', '1184 Farland Street', 'Brockton', '2401', 'United States'),
(145, 'Bianca A. Carone', 'Female', '1777 Elkview Drive', 'Hialeah', '33012', 'United States');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `tbl_customer`
--
ALTER TABLE `tbl_customer`
  ADD PRIMARY KEY (`CustomerID`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `tbl_customer`
--
ALTER TABLE `tbl_customer`
  MODIFY `CustomerID` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=146;


Install yajra datatables package


For use Datatable in Laravel 5.8 application, we have to download or install yajra datatables package in Laravel 5.8 application. For this we have go to command prompt and write following command.


composer require yajra/laravel-datatables-oracle


Once this yajra datatables package has been downloaded in Laravel 5.8 application, now we want to publish this package. For this we need to set providers and alias.
config/app.php

.....
'providers' => [
 ....
 Yajra\DataTables\DataTablesServiceProvider::class,
]
'aliases' => [
 ....
 'DataTables' => Yajra\DataTables\Facades\DataTables::class,
]
.....




Create Controller


In Laravel 5.8 application, we have require to make controller for handle http request. For this we have to go command prompt and write following command.


php artisan make:controller CustomSearchController


This command will make CustomSearchController.php file in app/Http/Controllers folder. In this file first we have to write use DB; statement for use Database operation. In this class we have make following method.

index() - This is the root method of this class. This method has load view blade file in browser with unique country name list for load in select box. This method has also received ajax request for load data in Datatable with all data or filter data in jQuery Datatable. Below you can find source code of this controller class also.

app/Http/Controllers/CustomSearchController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;

class CustomSearchController extends Controller
{
    function index(Request $request)
    {
     if(request()->ajax())
     {
      if(!empty($request->filter_gender))
      {
       $data = DB::table('tbl_customer')
         ->select('CustomerName', 'Gender', 'Address', 'City', 'PostalCode', 'Country')
         ->where('Gender', $request->filter_gender)
         ->where('Country', $request->filter_country)
         ->get();
      }
      else
      {
       $data = DB::table('tbl_customer')
         ->select('CustomerName', 'Gender', 'Address', 'City', 'PostalCode', 'Country')
         ->get();
      }
      return datatables()->of($data)->make(true);
     }
     $country_name = DB::table('tbl_customer')
          ->select('Country')
          ->groupBy('Country')
          ->orderBy('Country', 'ASC')
          ->get();
     return view('custom_search', compact('country_name'));
    }
}

?>


Create View Blade file


In Laravel 5.8 application, we have to make view blade file in resources/views folder and in this folder we have make custom_search.blade.php file. In this file we have add different library like jquery, bootstrap and jQuery Datatable plugin. In this file for custom search we have define two select box and two button which you can find in source code. In this file we have also write jquery code for load data in jquery Datatable plugin. Below you can find complete source code of this file below.

resources/views/custom_search.blade.php

<html>
 <head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Laravel 5.8 - Individual Column Search in Datatables 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 - Custom Search in Datatables using Ajax</h3>
     <br />
            <br />
            <div class="row">
                <div class="col-md-4"></div>
                <div class="col-md-4">
                    <div class="form-group">
                        <select name="filter_gender" id="filter_gender" class="form-control" required>
                            <option value="">Select Gender</option>
                            <option value="Male">Male</option>
                            <option value="Female">Female</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <select name="filter_country" id="filter_country" class="form-control" required>
                            <option value="">Select Country</option>
                            @foreach($country_name as $country)

                            <option value="{{ $country->Country }}">{{ $country->Country }}</option>

                            @endforeach
                        </select>
                    </div>
                    
                    <div class="form-group" align="center">
                        <button type="button" name="filter" id="filter" class="btn btn-info">Filter</button>

                        <button type="button" name="reset" id="reset" class="btn btn-default">Reset</button>
                    </div>
                </div>
                <div class="col-md-4"></div>
            </div>
            <br />
   <div class="table-responsive">
    <table id="customer_data" class="table table-bordered table-striped">
                    <thead>
                        <tr>
                            <th>Customer Name</th>
                            <th>Gender</th>
                            <th>Address</th>
                            <th>City</th>
                            <th>Postal Code</th>
                            <th>Country</th>
                        </tr>
                    </thead>
                </table>
   </div>
            <br />
            <br />
  </div>
 </body>
</html>

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

    fill_datatable();

    function fill_datatable(filter_gender = '', filter_country = '')
    {
        var dataTable = $('#customer_data').DataTable({
            processing: true,
            serverSide: true,
            ajax:{
                url: "{{ route('customsearch.index') }}",
                data:{filter_gender:filter_gender, filter_country:filter_country}
            },
            columns: [
                {
                    data:'CustomerName',
                    name:'CustomerName'
                },
                {
                    data:'Gender',
                    name:'Gender'
                },
                {
                    data:'Address',
                    name:'Address'
                },
                {
                    data:'City',
                    name:'City'
                },
                {
                    data:'PostalCode',
                    name:'PostalCode'
                },
                {
                    data:'Country',
                    name:'Country'
                }
            ]
        });
    }

    $('#filter').click(function(){
        var filter_gender = $('#filter_gender').val();
        var filter_country = $('#filter_country').val();

        if(filter_gender != '' &&  filter_gender != '')
        {
            $('#customer_data').DataTable().destroy();
            fill_datatable(filter_gender, filter_country);
        }
        else
        {
            alert('Select Both filter option');
        }
    });

    $('#reset').click(function(){
        $('#filter_gender').val('');
        $('#filter_country').val('');
        $('#customer_data').DataTable().destroy();
        fill_datatable();
    });

});
</script>


Set Route


Once all controller and view file code is ready, after this we have need to set route of controller method. For this we have to open routes/web.php file and write following code.

routes/web.php

Route::resource('customsearch', 'CustomSearchController');


Run Laravel Application


Lastly, We need to start Laravel server, for this we have to go command prompt and write following command.


php artisan serve


This command will start Laravel application and return base url of Laravel application. For run above example, we have to type http://127.0.0.1:8000/customsearch and you can run above example and check the feature of custom search in Laravel 5.8 Datatable using Ajax with yajra datatables package.

Monday, 24 June 2019

Laravel 5.8 Tutorial - File Upload with Progress Bar using Ajax



If you are looking for Laravel 5.8 web tutorial for learn How to Upload File or Image in Laravel 5.8 with Progress bar for display uploading process, then you have come on right place because you can find complete step by step tutorial for display uploading process in progress bar using Ajax jQuery in Laravel 5.8 framework. Here we have make tutorial on topic like Laravel file upload with Progress bar using Ajax jQuery.

Now in your mind one question is aris why we want to use progress bar while uploading of file. So, the answer is that if you have done file or image uploading in normal way then user can not see uploading process. So it is proper in web development, but if in your application you have to allowed large amount of File or image for uploading then at that time if you have not use progress bar then User of the system did not get idea about image or file has been done uploading or not. So, At that time if you have use progress bar while uploading of file then user can see how many percentage of uploading process of completed and how many percentage is remaining. So, this the main benefits of using progress bar for show uploading process on web page. In this post we will make feature like show progress bar while uploading of file in Laravel 5.8.

Here we have use jQuery Form plugin for submit form data by using Ajax. So for submit form data in Laravel 5.8 application, we have use jQuery form plugin. So, Image or file will be upload without refresh of web page and upload process will be display on web page in progress bar. Below you can find step by step process of how to use jQuery Ajax for upload file with progress bar in Laravel 5.8 framework.

  • Install Laravel 5.8 Framework
  • Create Controllers in Laravel 5.8 application
  • Create Blade File
  • Set Route




Install Laravel 5.8 Framework


For make Laravel 5.8 application, first we want to download and install Laravel 5.8 framework. For this we have go to command prompt, in which we want to first run "composer" command and after this we have to run following command. This command will download Laravel 5.8 framework in your define folder path.


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


Create Controllers in Laravel 5.8 application


In Laravel 5.8 application for handle http request we have to create controller. So for upload file here we have to create one controller for handle http request for upload file. For this we have go to command prompt and write following command.


php artisan make:controller FileUploadController


This command will make FileUploadController.php file in app/Http/Controllers folder. In this folder we have create two method.

index() - This method has load the file_upload.blade.php file in browser for select file from local computer.

upload() - This method has received request for upload file. This method has received ajax request for upload file. In this method first it has validate form data before upload. If form data has not proper then it has send error to Ajax request in JSON format. But suppose there is no any form data validation found then it will process for upload file and send success message to Ajax request in json format.

app/Http/Controllers/FileUploadController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use Validator;

class FileUploadController extends Controller
{
    function index()
    {
     return view('file_upload');
    }

    function upload(Request $request)
    {
     $rules = array(
      'file'  => 'required|image|max:2048'
     );

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

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

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

     $new_name = rand() . '.' . $image->getClientOriginalExtension();
     $image->move(public_path('images'), $new_name);

     $output = array(
         'success' => 'Image uploaded successfully',
         'image'  => '<img src="/images/'.$new_name.'" class="img-thumbnail" />'
        );

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

?>


Create Blade File


Laravel 5.8 has been use blade engine for display output in browser. So, we have to create view file under resources/views. In this folder we have create file_upload.blade.php file. In this file we have use jQuery library, Bootstrap library for display progress bar and jQuery form library for submit form data without refresh of web page. Here we have make form for select file from local computer. Under this file we have write jQuery code for display upload process in progress bar. After successfuly upload of image, it will be display on web page.

resources/views/file_upload.blade.php

<html>
 <head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Laravel 5.8 - File Upload with Progressbar 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>
        <script src="http://malsup.github.com/jquery.form.js"></script>
 </head>
 <body>
  <div class="container">    
     <br />
     <h3 align="center">Laravel 5.8 - File Upload with Progressbar using Ajax jQuery</h3>
     <br />
     <div class="panel panel-default">
                <div class="panel-heading">
                    <h3 class="panel-title">File Upload with Progressbar using Ajax jQuery</h3>
                </div>
                <div class="panel-body">
                    <br />
                    <form method="post" action="{{ route('upload') }}" enctype="multipart/form-data">
                      @csrf
                      <div class="row">
                            <div class="col-md-3" align="right"><h4>Select Image</h4></div>
                            <div class="col-md-6">
                              <input type="file" name="file" id="file" />
                            </div>
                            <div class="col-md-3">
                              <input type="submit" name="upload" value="Upload" class="btn btn-success" />
                            </div>
                        </div>
                    </form>
                    <br />
                    <div class="progress">
                      <div class="progress-bar" role="progressbar" aria-valuenow=""
                      aria-valuemin="0" aria-valuemax="100" style="width: 0%">
                        0%
                      </div>
                    </div>
                    <br />
                    <div id="success">

                    </div>
                    <br />
                </div>
            </div>
  </div>
 </body>
</html>

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

    $('form').ajaxForm({
      beforeSend:function(){
        $('#success').empty();
      },
      uploadProgress:function(event, position, total, percentComplete)
      {
        $('.progress-bar').text(percentComplete + '%');
        $('.progress-bar').css('width', percentComplete + '%');
      },
      success:function(data)
      {
        if(data.errors)
        {
          $('.progress-bar').text('0%');
          $('.progress-bar').css('width', '0%');
          $('#success').html('<span class="text-danger"><b>'+data.errors+'</b></span>');
        }
        if(data.success)
        {
          $('.progress-bar').text('Uploaded');
          $('.progress-bar').css('width', '100%');
          $('#success').html('<span class="text-success"><b>'+data.success+'</b></span><br /><br />');
          $('#success').append(data.image);
        }
      }
    });

});
</script>


Set Route


In Laravel 5.8 application, we have to set the route of controller method. For this we have to go to routes/web.php file and in this file we have to define route.

routes/web.php

<?php

Route::get('file-upload', 'FileUploadController@index');

Route::post('file-upload/upload', 'FileUploadController@upload')->name('upload');

?>


Lastly we have to run Laravel 5.8 application on file upload with progress bar. For this we have to command prompt and write following command.


php artisan serve


This command will run Laravel 5.8 application and for test above code you have to write following link in your browser tab.


http://127.0.0.1:8000/file-upload


For test the above code functionality, you have to hit following url in your browser then you can test Laravel 5.8 file upload with progress bar functionality is working or not.

Wednesday, 1 May 2019

Laravel 5.8 - Get Last Inserted ID



If you know how to get last inserted id in Laravel. If you not know then this post will help you to know how can we get last inserted record id in Laravel. Because in this post we have share Laravel tutorial on getting last inserted data id by 4 different method. So, from this post you can learn 4 method by which you can get the value of last inserted id in Laravel. Here we have use Laravel 5.8 framework in which we have describe 4 method by which we can get the value of last inserted id. In Web application development by using Laravel there are many place where we need to get the value of last inserted id value. So, here we have describe 4 different way by which we can get the last inserted id. In place place of web application we want to get last id of inserted record in Laravel application. Below you can find complete step by step process for get last id in Laravel.



Step 1 - Install Laravel 5.8 framework


First we need to download latest version of Laravel, for this we have to write following command in command prompt. It will install latest version of Laravel in you computer.


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


Step 2 - Make Database Connection


First we need to make database connection, for this we have to open .env file and in that file we have to define mysql database configuration, which we can see below.


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


Step 3 - Create Model


In this step we have to create model, because by using two method in which we need Laravel Eloquen model class. So we need to create model here. For this we have to go in command prompt and write follwing command. It will create LastId.php model file under app folder.


php artisan make:model LastId -m


After creating model file, in this we have to define table column name on which we have to do database operation. So, below you can find LastId.php model file.

app/LastId.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

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


Above model command has also create database migration file under database/migrations folder. In this file we have to define table column name with data type, which we have add in table. Below you can find migration file code.


<?php

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

class CreateLastIdsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('last_ids', 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('last_ids');
    }
}


Now we want to migrate this table defination to mysql database, for this we have to go command prompt and write following command, it will make last_ids table under mysql database.


php artisan migrate


Step 4 - Create Controller


For handle http request we need to make controller in Laravel, for this we have to go command prompt and write following command. It will make LastIdController.php in app/Http/Controllers folder.


php artisan make:controller LastIdController


In this controller file we have make two method. Below you can find two method description.

index() - This is the root method of this controller. It have load sample_form.blade.php file in browser.
getid() - This method has received ajax request for get the last inserted id. Below you can find 4 different method in Laravel by which we can get the value of last inserted id.
Method 1 - insertGetId() - This method has use Laravel Database class for get the value of last inserted id. For this we need to add use DB; line code at the header of this controller. Below you can find sample code of this method, how it has inserted data into database and return value of last inserted id in Laravel.





          $data = array(
       'first_name'  => $request->first_name,
       'last_name'  => $request->last_name
      );

        $last_id = DB::table('last_ids')
         ->insertGetId($data);

     return response()->json(['id' => $result->$last_id]);


Method 2 - lastInsertId() - This is second method by which we can get last inserted id in Laravel. For use this method, first we need to insert data into table by using Laravel Database library, and then after we need to use Laravel Database library getPDO() method with lastInsertID() method and this method will return last inserted id.


$data = array(
       'first_name'  => $request->first_name,
       'last_name'  => $request->last_name
      );

DB::table('last_ids')->insert($data);
$last_id = DB::getPDO()->lastInsertId();

return response()->json(['id' => $last_id]);


Method 3 - create() - This is third method by which we can get last inserted id in Laravel. This is Laravel Eloquent modal class method which has return data in array of object. So, we can get result in array of object by using create() method, and from object we can get last inserted id. For use this method we need to add use App\LastId; this line of code at the header of controller.


$data = array(
       'first_name'  => $request->first_name,
       'last_name'  => $request->last_name
      );

$result = LastId::create($data);

return response()->json(['id' => $result->id]);


Method 4 - save() - This is the 4th method by which we can get last inserted id in Laravel. This save() method is also Laravel Eloquent Modal class method. For use this method. We we need to create object of modal class and in that object we need to add form data as object. And last we have to use save() method. This method has return result in object of an array and from that object of array we can get value of last inserted id in Laravel.


$result = new LastId;
$result->first_name = $request->first_name;
$result->last_name = $request->last_name;
$result->save();

return response()->json(['id' => $result->id]);


By using above 4 method we can get the value of last inserted id in Laravel. After geting value of last inserted id, it will be send to Ajax request in json format. Whole source code of controller you can find below.

app/Http/Controllers/LastIdController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use DB;

use App\LastId;

class LastIdController extends Controller
{
    function index()
    {
     return view('sample_form');
    }

    function getid(Request $request)
    {
     if($request->ajax())
     {
      $data = array(
       'first_name'  => $request->first_name,
       'last_name'   => $request->last_name
      );

            //Method 1
      /*$last_id = DB::table('last_ids')
         ->insertGetId($data);*/

            //Method 2
      /*DB::table('last_ids')->insert($data);
      $last_id = DB::getPDO()->lastInsertId();*/

            //Method 3
      /*$result = LastId::create($data);*/

            //Method 4
      $result = new LastId;
      $result->first_name = $request->first_name;
      $result->last_name = $request->last_name;
      $result->save();

      return response()->json(['id' => $result->id]);
     }
    }
}



Step 5 - Create View File


Below you can find source code of sample_form.blade.php file. This file has been store under resources/views folder. In this file you can find HTML code for form and Ajax jQuery code for submit form data to server script.


<html>
 <head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Laravel 5.8 - Get Last Inserted ID</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">Laravel 5.8 - Get Last Inserted ID</h3>
     <br />
     <div class="row">
      <div class="col-md-3">

      </div>
      <div class="col-md-6">
     <form method="post" id="sample_form">
      @CSRF
      <div class="form-group">
       <label>First Name</label>
       <input type="text" name="first_name" class="form-control" />
      </div>
      <div class="form-group">
       <label>Last Name</label>
       <input type="text" name="last_name" class="form-control" />
      </div>
      <div class="form-group">
       <input type="submit" name="submit" class="btn btn-info" value="Submit" />
      </div>
     </form>
     <div id="last_inserted_id"></div>
    </div>
    <div class="col-md-3">
    </div>
   </div>
  </div>
 </body>
</html>
<script>
$(document).ready(function(){
 $('#sample_form').on('submit', function(event){

  event.preventDefault();
  $.ajax({
   url:"{{ route('last-id/getid') }}",
   method:"POST",
   data:$(this).serialize(),
   dataType:"json",
   success:function(data){
    $('#sample_form')[0].reset();
    $('#last_inserted_id').html('Last Inserted ID - ' + data.id);
   }
  })
 });
});
</script>


Step 6 - Set Route


In Laravel application we need to set route for controller method. For this we have to open routes/web.php file. In this file you have to write following code for set route.


<?php

Route::get('last-id', 'LastIdController@index');

Route::post('last-id/getid', 'LastIdController@getid')->name('last-id/getid');

?>


For learn laravel application, we have to go to command prompt and write following command.


php artisan serve


Above command will start laravel server and it will return base url of your laravel application. For run this last inseted id application we need to write following url.


http://127.0.0.1:8000/last-id




Sunday, 21 April 2019

How to Join Multiple Table in Laravel 5.8



This is one more tutorial on Laravel 5.8 framework and in this post you can find how to join multiple table in Laravel 5.8 framework. Here we will take example of fetch data from two or more table by using inner join in Laravel 5.8 and display on web page. If you are looking for learn how to make inner join with multiple table in Laravel 5.8 then this tutorial will help you because here we have take simple example for fetch data from multiple table from scratch.

Join Table means returns the records or rows which are present in both table, for this there is at least one table column match between two table. So, this type of join we have to make in Laravel 5.8 framework. There is major benefits of join of multiple table is that in one query execution you can fetch data from multiple table. Below you can find source of Laravel 5.8 join multiple table by using inner join.







JoinTableController.php


app/Http/Controllers/>JoinTableController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;

class JoinTableController extends Controller
{
    function index()
    {
     $data = DB::table('city')
       ->join('state', 'state.state_id', '=', 'city.state_id')
       ->join('country', 'country.country_id', '=', 'state.country_id')
       ->select('country.country_name', 'state.state_name', 'city.city_name')
       ->get();
     return view('join_table', compact('data'));
    }
}
?>


join_table.blade.php


resources/views/join_table.blade.php

<html>
 <head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Laravel 5.8 - Join Multiple Table</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">Laravel 5.8 - Join Multiple Table</h3>
     <br />
   <div class="table-responsive">
    <table class="table table-bordered table-striped">
           <thead>
            <tr>
                <th>Country</th>
                <th>State</th>
                <th>City</th>
            </tr>
           </thead>
           <tbody>
           @foreach($data as $row)
            <tr>
             <td>{{ $row->country_name }}</td>
             <td>{{ $row->state_name }}</td>
             <td>{{ $row->city_name }}</td>
            </tr>
           @endforeach
           </tbody>
       </table>
   </div>
  </div>
 </body>
</html>


web.php


routes/web.php

Route::get('join-table', 'JoinTableController@index');


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