[Latest News][6]

B.Sc.CSIT
Blogs
Laravel
Learn
News
Rentonnepal
Technology
A Complete Online Magazine

AddThis

Laravel 5 Ajax CRUD with Pagination example and demo from scratch

In this tutorials, I going to give you how to create jquery Ajax CRUD(Create, Read, Update and Delete) in your laravel 5 application. I write just few step to follow you can make simple crud application with jquery pagination in your laravel 5 project.



In this example i used several jquery Plugin for fire Ajax, Ajax pagination, Bootstrap, Bootstrap Validation, notification as listed bellow.


  • Jquery
  • Bootstrap
  • twbsPagination js
  • Validator JS(Bootstrap form validation example with demo using validator.js plugin)
  • toastr JS(Jquery notification popup box example using toastr JS plugin with demo)


this simple ajax crud example, i created "Item Management" with you can do several option like as bellow:

1. Item Listing

2. Item Create

3. Item Edit

4. Item Delete

you can implement crud application from scratch, so no worry if you can implement through bellow simple step. After create successful example, you will find layout as bellow:

Step 1: Laravel Installation
In first step, If you haven't installed Laravel in your system then you have to run bellow command and get fresh Laravel project.

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

Step 2: Create items table and model
In this step we have to create migration for items table using Laravel 5 php artisan command, so first fire bellow command:

php artisan make:migration create_items_table

After this command you will find one file in following path database/migrations and you have to put bellow code in your migration file for create items table.

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

class CreateItemsTable extends Migration
{

    public function up()
    {
        Schema::create('items', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->text('description');
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::drop("items");
    }
}

After create "items" table you should create Item model for items, so first create file in this path app/Item.php and put bellow content in item.php file:

app/Item.php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Item extends Model
{

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

}

Step 3: Add Route and Controller
Now we have to add route for items CRUD and pagination, in this example i added resource route and one for manage-item-ajax for application, if we add resource route then it will add index, create, edit and delete route automatically. So add bellow line in your route file.

app/Http/routes.php

Route::get('manage-item-ajax', 'ItemAjaxController@manageItemAjax');
Route::resource('item-ajax', 'ItemAjaxController');

Ok, now we should create new controller as ItemAjaxController in this path app/Http/Controllers/ItemAjaxController.php. this controller will manage all route method:

app/Http/Controllers/ItemAjaxController.php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Item;

class ItemAjaxController extends Controller
{

    public function manageItemAjax()
    {
        return view('manage-item-ajax');
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $items = Item::latest()->paginate(5);
        return response()->json($items);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $create = Item::create($request->all());
        return response()->json($create);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        $edit = Item::find($id)->update($request->all());
        return response()->json($edit);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        Item::find($id)->delete();
        return response()->json(['done']);
    }
}


Step 4: Create Blade File
In this step we have to create only one blade file that will manage create, update and delete operation of items module with jquery.

So, let's create manage-item-ajax.php file on following way:

resources/views/manage-item-ajax.blade.php

<!DOCTYPE html>
<html>
<head>
<title>Laravel Ajax CRUD Example</title>
<meta name="csrf-token" content="{{ csrf_token() }}">
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha/css/bootstrap.css">
</head>
<body>

<div class="container">

<div class="row">
   <div class="col-lg-12 margin-tb">
       <div class="pull-left">
           <h2>Laravel Ajax CRUD Example</h2>
       </div>
       <div class="pull-right">
<button type="button" class="btn btn-success" data-toggle="modal" data-target="#create-item">
 Create Item
</button>
       </div>
   </div>
</div>

<table class="table table-bordered">
<thead>
   <tr>
<th>Title</th>
<th>Description</th>
<th width="200px">Action</th>
   </tr>
</thead>
<tbody>
</tbody>
</table>

<ul id="pagination" class="pagination-sm"></ul>

   <!-- Create Item Modal -->
<div class="modal fade" id="create-item" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
 <div class="modal-dialog" role="document">
   <div class="modal-content">
     <div class="modal-header">
       <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
       <h4 class="modal-title" id="myModalLabel">Create Item</h4>
     </div>
     <div class="modal-body">

      <form data-toggle="validator" action="{{ route('item-ajax.store') }}" method="POST">
      <div class="form-group">
<label class="control-label" for="title">Title:</label>
<input type="text" name="title" class="form-control" data-error="Please enter title." required />
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<label class="control-label" for="title">Description:</label>
<textarea name="description" class="form-control" data-error="Please enter description." required></textarea>
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<button type="submit" class="btn crud-submit btn-success">Submit</button>
</div>
      </form>
     </div>
   </div>
 </div>
</div>

<!-- Edit Item Modal -->
<div class="modal fade" id="edit-item" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
 <div class="modal-dialog" role="document">
   <div class="modal-content">
     <div class="modal-header">
       <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
       <h4 class="modal-title" id="myModalLabel">Edit Item</h4>
     </div>
     <div class="modal-body">

      <form data-toggle="validator" action="/item-ajax/14" method="put">
      <div class="form-group">
<label class="control-label" for="title">Title:</label>
<input type="text" name="title" class="form-control" data-error="Please enter title." required />
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<label class="control-label" for="title">Description:</label>
<textarea name="description" class="form-control" data-error="Please enter description." required></textarea>
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-success crud-submit-edit">Submit</button>
</div>
      </form>

     </div>
   </div>
 </div>
</div>

</div>

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha/js/bootstrap.min.js"></script>

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/twbs-pagination/1.3.1/jquery.twbsPagination.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/1000hz-bootstrap-validator/0.11.5/validator.min.js"></script>

<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/js/toastr.min.js"></script>
        <link href="//cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/css/toastr.min.css" rel="stylesheet">

        <script type="text/javascript">
      var url = "<?php echo route('item-ajax.index')?>";
        </script>
        <script src="/js/item-ajax.js"></script> 

</body>
</html>

Step 5: Create JS File
In last step we require to create one item-ajax.js file, first we have to create new folder "js" in public directory and then create item-ajax.js file inside of this folder.

item-ajax.js file through we can manage item pagination, create edit delete task and also ajax method.

public/js/item-ajax.js

var page = 1;
var current_page = 1;
var total_page = 0;
var is_ajax_fire = 0;

manageData();

/* manage data list */
function manageData() {
    $.ajax({
        dataType: 'json',
        url: url,
        data: {page:page}
    }).done(function(data){

    total_page = data.last_page;
    current_page = data.current_page;

    $('#pagination').twbsPagination({
       totalPages: total_page,
       visiblePages: current_page,
       onPageClick: function (event, pageL) {
        page = pageL;
                if(is_ajax_fire != 0){
         getPageData();
                }
       }
   });

    manageRow(data.data);
        is_ajax_fire = 1;
    });
}

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

/* Get Page Data*/
function getPageData() {
$.ajax({
    dataType: 'json',
    url: url,
    data: {page:page}
}).done(function(data){
manageRow(data.data);
});
}

/* Add new Item table row */
function manageRow(data) {
var rows = '';
$.each( data, function( key, value ) {
  rows = rows + '<tr>';
  rows = rows + '<td>'+value.title+'</td>';
  rows = rows + '<td>'+value.description+'</td>';
  rows = rows + '<td data-id="'+value.id+'">';
                rows = rows + '<button data-toggle="modal" data-target="#edit-item" class="btn btn-primary edit-item">Edit</button> ';
                rows = rows + '<button class="btn btn-danger remove-item">Delete</button>';
                rows = rows + '</td>';
  rows = rows + '</tr>';
});

$("tbody").html(rows);
}

/* Create new Item */
$(".crud-submit").click(function(e){
    e.preventDefault();
    var form_action = $("#create-item").find("form").attr("action");
    var title = $("#create-item").find("input[name='title']").val();
    var description = $("#create-item").find("textarea[name='description']").val();

    $.ajax({
        dataType: 'json',
        type:'POST',
        url: form_action,
        data:{title:title, description:description}
    }).done(function(data){
        getPageData();
        $(".modal").modal('hide');
        toastr.success('Item Created Successfully.', 'Success Alert', {timeOut: 5000});
    });

});

/* Remove Item */
$("body").on("click",".remove-item",function(){
    var id = $(this).parent("td").data('id');
    var c_obj = $(this).parents("tr");
    $.ajax({
        dataType: 'json',
        type:'delete',
        url: url + '/' + id,
    }).done(function(data){
        c_obj.remove();
        toastr.success('Item Deleted Successfully.', 'Success Alert', {timeOut: 5000});
        getPageData();
    });
});

/* Edit Item */
$("body").on("click",".edit-item",function(){
    var id = $(this).parent("td").data('id');
    var title = $(this).parent("td").prev("td").prev("td").text();
    var description = $(this).parent("td").prev("td").text();
    $("#edit-item").find("input[name='title']").val(title);
    $("#edit-item").find("textarea[name='description']").val(description);
    $("#edit-item").find("form").attr("action",url + '/' + id);
});

/* Updated new Item */
$(".crud-submit-edit").click(function(e){
    e.preventDefault();
    var form_action = $("#edit-item").find("form").attr("action");
    var title = $("#edit-item").find("input[name='title']").val();
    var description = $("#edit-item").find("textarea[name='description']").val();

    $.ajax({
        dataType: 'json',
        type:'PUT',
        url: form_action,
        data:{title:title, description:description}
    }).done(function(data){
        getPageData();
        $(".modal").modal('hide');
        toastr.success('Item Updated Successfully.', 'Success Alert', {timeOut: 5000});
    });
});

Ok, so let's test.....

No comments:

Post a Comment

Start typing and press Enter to search