FahmidasClassroom

Learn by easy steps

Lara Datatables

Simple Laravel 7 CRUD using modal is shown in the previous tutorial. DataTables is a popular Jquery plugin to work with the large list of data with pagination and search option. How you can use DataTables in Laravel 7 and implement CRUD operation are shown in this tutorial.

Steps:

1. First of all you have to install a fresh copy of laravel 7. Go to the folder where you want create Laravel project and open command prompt. Run the following command to create a new Laravel 7 project.

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

2. Go to the project folder and run the following command to check the installed version of the laravel.

php artisan --version

3. Run the project from xampp server

http://localhost/laravelpro/public

4. Create a database named laravel and open .env file to set the database connection.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=''

5. The following migrate command to create the users table.

 php artisan migrate

6. Run the following command to install DataTables in Laravel 7.

composer require yajra/laravel-datatables-oracle:"~9.0"

7. Open config/app.php file and add the following lines in the correct place.

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

8. Run the following commands to publish the vender  and re-compile the laravel after installing DataTables.

php artisan vendor:publish
 composer dump-autoload

9. Run the following command to open tinker console.

php artisan tinker

10. Run the following command to insert 50 dummy data into users table.

factory(App\User::class, 50)->create();

10. Run the following command to create user resource controller.

 php artisan make:controller UserController --resource

11. Open UserController from app/Http/Cotrollers folder. Modify the code with the following code.

<?php

namespace App\Http\Controllers;

use App\User;
use Illuminate\Http\Request;
use DataTables;
use Redirect,Response;

class UserController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index(Request $request)
{
if ($request->ajax()) {
$data = User::latest()->get();
return Datatables::of($data)
->addIndexColumn()
->addColumn('action', function($row){

$action = '<a class="btn btn-info" id="show-user" data-toggle="modal" data-id='.$row->id.'>Show</a>
<a class="btn btn-success" id="edit-user" data-toggle="modal" data-id='.$row->id.'>Edit </a>
<meta name="csrf-token" content="{{ csrf_token() }}">
<a id="delete-user" data-id='.$row->id.' class="btn btn-danger delete-user">Delete</a>';

return $action;

})
->rawColumns(['action'])
->make(true);
}

return view('users');
}

public function store(Request $request)
{

$r=$request->validate([
'name' => 'required',
'email' => 'required',

]);

$uId = $request->user_id;
User::updateOrCreate(['id' => $uId],['name' => $request->name, 'email' => $request->email]);
if(empty($request->user_id))
$msg = 'User created successfully.';
else
$msg = 'User data is updated successfully';
return redirect()->route('users.index')->with('success',$msg);
}

/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/

public function show($id)
{
$where = array('id' => $id);
$user = User::where($where)->first();
return Response::json($user);
//return view('users.show',compact('user'));
}

/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/

public function edit($id)
{
$where = array('id' => $id);
$user = User::where($where)->first();
return Response::json($user);
}

/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/

public function destroy($id)
{
$user = User::where('id',$id)->delete();
return Response::json($user);
//return redirect()->route('users.index');
}
}

12. Open web.php from routes folder and add the following code at the end of the file.

 Route::resource('users','UserController');
 Route::get('users/{id}/edit/','UserController@edit');

13. Create a blade file named users.blade.php  under the resources/views/ folder.
14.  Add the following code to users.blade.php.

<!DOCTYPE html>
<html>
<head>
<title>Laravel 7 CRUD using Datatables</title>
<meta name="csrf-token" content="{{ csrf_token() }}">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" />
<link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet">
<link href="https://cdn.datatables.net/1.10.19/css/dataTables.bootstrap4.min.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.js"></script>
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/dataTables.bootstrap4.min.js"></script>
<script>
error=false

function validate()
{
if(document.userForm.name.value !='' && document.userForm.email.value !='' )
document.userForm.btnsave.disabled=false
else
document.userForm.btnsave.disabled=true
}
</script>
</head>
<body>

<div class="container">
<h1 align="center">Laravel 7 CRUD using Datatables</h1>
<br/>
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-right">
<a class="btn btn-success mb-2" id="new-user" data-toggle="modal">New User</a>
</div>
</div>
</div>

<table class="table table-bordered data-table" >
<thead>
<tr id="">
<th width="5%">No</th>
<th width="5%">Id</th>
<th width="30%">Name</th>
<th width="30%">Email</th>
<th width="20%">Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>

<!-- Add and Edit customer modal -->
<div class="modal fade" id="crud-modal" aria-hidden="true" >
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="userCrudModal"></h4>
</div>
<div class="modal-body">
<form name="userForm" action="{{ route('users.store') }}" method="POST">
<input type="hidden" name="user_id" id="user_id" >
@csrf
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Name:</strong>
<input type="text" name="name" id="name" class="form-control" placeholder="Name" onchange="validate()" >
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>Email:</strong>
<input type="text" name="email" id="email" class="form-control" placeholder="Email" onchange="validate()">
</div>
</div>

<div class="col-xs-12 col-sm-12 col-md-12 text-center">
<button type="submit" id="btn-save" name="btnsave" class="btn btn-primary" disabled>Save</button>
<a href="{{ route('users.index') }}" class="btn btn-danger">Cancel</a>
</div>
</div>
</form>
</div>
</div>
</div>
</div>

<!-- Show user modal -->
<div class="modal fade" id="crud-modal-show" aria-hidden="true" >
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="userCrudModal-show"></h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-xs-2 col-sm-2 col-md-2"></div>
<div class="col-xs-10 col-sm-10 col-md-10 ">

<table class="table-responsive ">
<tr height="50px"><td><strong>Name:</strong></td><td id="sname"></td></tr>
<tr height="50px"><td><strong>Email:</strong></td><td id="semail"></td></tr>

<tr><td></td><td style="text-align: right "><a href="{{ route('users.index') }}" class="btn btn-danger">OK</a> </td></tr>
</table>
</div>
</div>
</div>
</div>
</div>
</div>

</body>

<script type="text/javascript">

$(document).ready(function () {

var table = $('.data-table').DataTable({
processing: true,
serverSide: true,
ajax: "{{ route('users.index') }}",
columns: [
{data: 'DT_RowIndex', name: 'DT_RowIndex'},
{data: 'id', name: 'id'},
{data: 'name', name: 'name'},
{data: 'email', name: 'email'},
{data: 'action', name: 'action', orderable: false, searchable: false},
]
});

/* When click New customer button */
$('#new-user').click(function () {
$('#btn-save').val("create-user");
$('#user').trigger("reset");
$('#userCrudModal').html("Add New User");
$('#crud-modal').modal('show');
});

/* Edit customer */
$('body').on('click', '#edit-user', function () {
var user_id = $(this).data('id');
$.get('users/'+user_id+'/edit', function (data) {
$('#userCrudModal').html("Edit User");
$('#btn-update').val("Update");
$('#btn-save').prop('disabled',false);
$('#crud-modal').modal('show');
$('#user_id').val(data.id);
$('#name').val(data.name);
$('#email').val(data.email);

})
});
/* Show customer */
$('body').on('click', '#show-user', function () {
var user_id = $(this).data('id');
$.get('users/'+user_id, function (data) {

$('#sname').html(data.name);
$('#semail').html(data.email);

})
$('#userCrudModal-show').html("User Details");
$('#crud-modal-show').modal('show');
});

/* Delete customer */
$('body').on('click', '#delete-user', function () {
var user_id = $(this).data("id");
var token = $("meta[name='csrf-token']").attr("content");
confirm("Are You sure want to delete !");

$.ajax({
type: "DELETE",
url: "http://localhost/laravelpro/public/users/"+user_id,
data: {
"id": user_id,
"_token": token,
},
success: function (data) {

//$('#msg').html('Customer entry deleted successfully');
//$("#customer_id_" + user_id).remove();
table.ajax.reload();
},
error: function (data) {
console.log('Error:', data);
}
});
});

});

</script>
</html>

15.  Now, Laravel crud with DataTables project is ready to run.

The video tutorial of the steps is given below.