Laravel 5 Crud Operations Using Ajax

Laravel 5 Crud Operations Using Ajax

By : Laravellogic Created : July 11, 2018 View : 845

Hello friend, In this post I'm making a Laravel CRUD ( Create / Insert, Read, Update, Delete ) system with Ajax jQuery. I made this project simplest and the easiest way to make people understand how crud system works in Laravel using Ajax jQuery, just follow all below step.

many developer create crud operation using ajax but crud operation with pagination makes it difficult, So today we have done simpale way crud opration with Ajax.

Ajax is a javascript that fast outputs data without loading the page, So that many developers show the problems used in Ajax in the laravel applications, If you want to use Ajax in your laravel application, you're in the right place.

first you are Look here below image, i created Laravel 5 Crud Operations Using Ajax file structure. which You will be useful to understand.

Laravel 5 crud with ajex file structure

You are ready go start below step.

Step 1: Create Student table using Migration

First you need a student table in your database if you want to take data from another table on your website, it must be in the table. So let's first make the table.

php artisan make:migration create_students_table

After run above command, goto database/migrations/ and open students table and add following code.

<?php

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

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

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

Save the above file and set the student table variable after following command

php artisan migrate

so you have create a students table automatically in your database run above command.

Step 2: Create students Model And Controller

now you are create a model and controller, it below single command to create a model and controller automatically.

php artisan make:model Student -c

you can use -c to create two file model and controller automatically

After create model goto app/Students.php file and add following code

app/Students.php

<?php
  
namespace App;

use Illuminate\Database\Eloquent\Model;

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

After create controller goto app/Http/Controller/StudentsController.php file and add following code

app/Http/Controller/StudentsController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Student;

class StudentController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function myStudents()
    {
        return view('student.index');
    }

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

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

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

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

Step 3: Create Route

Next, you are add below 2 route

Route::get('students-list', 'StudentController@myStudents')->name('myStudents');
Route::resource('students','StudentController');

We are use Route::resource to create automatically route following image

Laravel-5 Crud Operations with pagination Using Ajex route

Step 4: Create view file

First create student folder in views path like resources/views/studen

now Inside of it we are create 3 view file,In which index file is a main file and create and edit file is a modal(popup) file which include in index file.

To do that for the pagination, we need 2 cdn files (1) Bootstrap 4   (2) jquery.twbsPagination.min.js

(1)resources/views/student/index.blade.php

<!DOCTYPE html>
<html>
<head>
  <title>Laravel 5 Ajax CRUD Example</title>
  <meta name="csrf-token" content="{{ csrf_token() }}">
  <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha/css/bootstrap.css" rel="stylesheet" type="text/css">
</head>
<body>
  <div class="container">
    <div class="row">
        <div class="col-lg-12 margin-tb">
            <div class="text-center">
                <h2>Laravel 5 Ajax CRUD Example - Demo</h2>
            </div>
            <div class="pull-right">
              <button type="button" class="btn btn-success create_student" data-toggle="modal" data-target="#create-student">Create New Student</button>
            </div>
        </div>
    </div>
    <table class="table table-bordered">
      <thead>
          <tr>
        <th>First Name</th>
        <th>Last Name</th>
        <th width="200px">Action</th>
          </tr>
      </thead>
      <tbody>
      </tbody>
    </table>

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

    <!-- Create Student Modal -->
    @include('student.create')
    <!-- Edit Student Modal -->
    @include('student.edit')
  </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('students.index')?>";
  </script>
  <script src="/js/ajax.js"></script> 
</body>
</html>

(2)resources/views/student/create.blade.php

<!-- Ctrete Student Modal -->
<div class="modal fade" id="create-student" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog" role="document">
  
    <!-- Modal content-->
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">×</button>
        <h4 class="modal-title">Crete student</h4>
      </div>
      <div class="modal-body">
        <form class="form-horizontal" action="{{ URL::route('students.store') }}" method="post" data-toggle="validator">
          <div class="form-group">
            <label for="email">First Nmae:</label>
            <input type="text" class="form-control" id="first_name" name="first_name" data-error="Please enter first name." required />
            <div class="help-block with-errors"></div>
          </div>
          <div class="form-group">
            <label for="email">Last Nmae:</label>
            <input type="text" class="form-control" id="last_name" name="last_name" data-error="Please enter last name." required />
            <div class="help-block with-errors"></div>
          </div>
          <div class="form-group">        
            <button type="submit" class="btn btn-success data-submit">Add</button>
          </div>
        </form>
      </div>
    </div>
    
  </div>
</div>

(3)resources/views/student/edit.blade.php

<!-- Edit Student Modal -->
<div class="modal fade" id="edit-student" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog" role="document">
  
    <!-- Modal content-->
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">×</button>
        <h4 class="modal-title">Edit student</h4>
      </div>
      <div class="modal-body">
        <form class="form-horizontal" action="" method="post" data-toggle="validator">
          <div class="form-group">
            <label for="email">First Nmae:</label>
            <input type="text" class="form-control" id="first_name" name="first_name" data-error="Please enter first name." required />
            <div class="help-block with-errors"></div>
          </div>
          <div class="form-group">
            <label for="email">Last Nmae:</label>
            <input type="text" class="form-control" id="last_name" name="last_name" data-error="Please enter last name." required />
            <div class="help-block with-errors"></div>
          </div>
          <div class="form-group">        
            <button type="submit" class="btn btn-success edit-data-submit">Add</button>
          </div>
        </form>
      </div>
    </div>
    
  </div>
</div>

Step 5: Create AJax file

we are manage insert update delete and pagination function in this ajax file

Now we are create a ajax.js file in public/js path and add following code in ajax.js file

public/js/ajax.js

var page = 1;
var current_page = 1;
var total_page = 0;
var first_time = 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, last_page) {
                page = last_page;
                if(first_time != 0){
                  getPageData();
                }
            }
        });


        manageRow(data.data);
        first_time = 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 Student table record */
function manageRow(data) {
    var rows = '';
    $.each( data, function( key, value ) {
        rows = rows + '<tr>';
        rows = rows + '<td>'+value.first_name+'</td>';
        rows = rows + '<td>'+value.last_name+'</td>';
        rows = rows + '<td data-id="'+value.id+'">';
        rows = rows + '<button data-toggle="modal" data-target="#edit-student" class="btn btn-primary edit-student">Edit</button> ';
        rows = rows + '<button class="btn btn-danger remove-student">Delete</button>';
        rows = rows + '</td>';
        rows = rows + '</tr>';
    });


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

/* Create new Student table record */
$(".create_student").click(function(e){
    $("#create-student").find("input[name='first_name']").val('');
    $("#create-student").find("input[name='last_name']").val('');
});

/* Create new Student table record */
$(".data-submit").click(function(e){
    e.preventDefault();
    var form_action = $("#create-student").find("form").attr("action");
    var first_name = $("#create-student").find("input[name='first_name']").val();
    var last_name = $("#create-student").find("input[name='last_name']").val();
    $.ajax({
        dataType: 'json',
        type:'POST',
        url: form_action,
        data:{first_name:first_name, last_name:last_name}
    }).done(function(data){
        getPageData();
        $(".modal").modal('hide');
        toastr.success('Post Created Successfully.', 'Success Alert', {timeOut: 5000});
    });
});


/* Edit Student create (open popup) */
$("body").on("click",".edit-student",function(){
    var id = $(this).parent("td").data('id');
    var first_name = $(this).parent("td").prev("td").prev("td").text();
    var last_name = $(this).parent("td").prev("td").text();

 
    $("#edit-student").find("input[name='first_name']").val(first_name);
    $("#edit-student").find("input[name='last_name']").val(last_name);
    $("#edit-student").find("form").attr("action",url + '/' + id);
});


/* Updated new Student table record */
$(".edit-data-submit").click(function(e){
    e.preventDefault();
    var form_action = $("#edit-student").find("form").attr("action");
    var first_name = $("#edit-student").find("input[name='first_name']").val();
    var last_name = $("#edit-student").find("input[name='last_name']").val();


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

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

Now let's start full crud operations with pagination using ajax, And find you any problem please comment below