How to Add Data in DataTable in Laravel Crud

In this tutorial I’m going to describe how to add data in DataTable in laravel 8 we will create single page companies ajax crud application (SPA) using dataTables js, modal and jQuery in laravel 8.

Laravel 8 Ajax CRUD Tutorial using Datatable JS
Step 1 – Download Laravel 8 App
Step 2 – Database Configuration
Step 3 – Installing Yajra Datatables
Step 4 – Make Model & Migration
Step 5 – Make Routes
Step 6 – Create AJAX CRUD Datatables Controller
Step 7 – Create Blade Views File
companies.blade.php
company-action.blade.php
Step 8 – Run Development Server

Step 1 — Download Laravel 8 App

1st step Install laravel project and new setup, lets open the terminal C:\xampp\htdocs and paste below code

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

Step 2 — Database Configuration

Setup database with your installed laravel 8 project . lets go to .env folder and put database name and connect to database.

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

Next run this command

php artisan migrate

Step 3 — Installing Yajra Datatables

composer require yajra/laravel-datatables-oracle

Then configure datatables package. So go to config directory and open app.php file. And add the following service providers into app.php file:

Go to -> config/app.php and put in providers section

'providers' => [

Yajra\Datatables\DatatablesServiceProvider::class,
],

'aliases' => [

'Datatables' => Yajra\Datatables\Facades\Datatables::class,
]

Then publish laravel datatables vendor package by using below command:

php artisan vendor:publish

Step 4 — Make Model & Migration

php artisan make:model Company -m

Simply copy this code and paste in companies model

<?php

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

class CreateCompaniesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('companies', function (Blueprint $table) {
$table->id();
$table->timestamps();
$table->string('name');
$table->string('email');
$table->string('address');
});
}

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

Lets migrate table to database run this command

php artisan migrate

After that, lets go to app/models directory and open company.php model file. Then add the following code into it:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Company extends Model
{

protected $fillable =['name', 'email', 'address'];

}

Step 5 — Make Routes

<?php

use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
return view('welcome');
});

use App\Http\Controllers\DataTableAjaxCRUDController;

Route::get('ajax-crud-datatable', [DataTableAjaxCRUDController::class, 'index']);
Route::post('store-company', [DataTableAjaxCRUDController::class, 'store']);
Route::post('edit-company', [DataTableAjaxCRUDController::class, 'edit']);
Route::post('delete-company', [DataTableAjaxCRUDController::class, 'destroy']);

Step 6 — Create AJAX CRUD Datatables Controller

php artisan make:controller DataTableAjaxCRUDController -r

Lets go to controller and copy below code and paste there

<?php

namespace App\Http\Controllers;


use Illuminate\Http\Request;
use App\Company;
class DataTableAjaxCRUDController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
if(request()->ajax()) {
return datatables()->of(Company::select('*'))
->addColumn('action', 'company-action')
->rawColumns(['action'])
->addIndexColumn()
->make(true);
}
return view('companies');
}

/**
* 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)
{
$companyId = $request->id;

$company = Company::updateOrCreate(
[
'id' => $companyId
],
[
'name' => $request->name,
'email' => $request->email,
'address' => $request->address
]);

return Response()->json($company);
}

/**
* 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)
{
$where = array('id' => $request->id);
$company = Company::where($where)->first();

return Response()->json($company);
}

/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
//
}

/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$company = Company::where('id','$request->id')->delete();
return Response()->json($company);
}
}

Step 6 — Create Blade Views File

Create two blade views file, which is following:

  • companies.blade.php

Next go to companies.blade.php file and paste below code

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Laravel 8 AJAX CRUD using DataTable js Tutorial From Scratch - Tutsmake.com</title>
<meta name="csrf-token" content="{{ csrf_token() }}">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" >
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
<link href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css" rel="stylesheet">
<script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>
</head>
<body>
<div class="container mt-2">
<div class="row">
<div class="col-lg-12 margin-tb">
<div class="pull-left">
<h2>Laravel 8 Ajax CRUD DataTables Tutorial</h2>
</div>
<div class="pull-right mb-2">
<a class="btn btn-success" onClick="add()" href="javascript:void(0)"> Create Company</a>
</div>
</div>
</div>
@if ($message = Session::get('success'))
<div class="alert alert-success">
<p>{{ $message }}</p>
</div>
@endif
<div class="card-body">
<table class="table table-bordered" id="ajax-crud-datatable">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Email</th>
<th>Address</th>
<th>Created at</th>
<th>Action</th>
</tr>
</thead>
</table>
</div>
</div>
<!-- boostrap company model -->
<div class="modal fade" id="company-modal" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="CompanyModal"></h4>
</div>
<div class="modal-body">
<form action="javascript:void(0)" id="CompanyForm" name="CompanyForm" class="form-horizontal" method="POST" enctype="multipart/form-data">
<input type="hidden" name="id" id="id">
<div class="form-group">
<label for="name" class="col-sm-2 control-label">Company Name</label>
<div class="col-sm-12">
<input type="text" class="form-control" id="name" name="name" placeholder="Enter Company Name" maxlength="50" required="">
</div>
</div>
<div class="form-group">
<label for="name" class="col-sm-2 control-label">Company Email</label>
<div class="col-sm-12">
<input type="email" class="form-control" id="email" name="email" placeholder="Enter Company Email" maxlength="50" required="">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Company Address</label>
<div class="col-sm-12">
<input type="text" class="form-control" id="address" name="address" placeholder="Enter Company Address" required="">
</div>
</div>
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-primary" id="btn-save">Save changes
</button>
</div>
</form>
</div>
<div class="modal-footer">
</div>
</div>
</div>
</div>
<!-- end bootstrap model -->
</body>
<script type="text/javascript">
$(document).ready( function () {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#ajax-crud-datatable').DataTable({
processing: true,
serverSide: true,
ajax: "{{ url('ajax-crud-datatable') }}",
columns: [
{ data: 'id', name: 'id' },
{ data: 'name', name: 'name' },
{ data: 'email', name: 'email' },
{ data: 'address', name: 'address' },
{ data: 'created_at', name: 'created_at' },
{data: 'action', name: 'action', orderable: false},
],
order: [[0, 'desc']]
});
});
function add(){
$('#CompanyForm').trigger("reset");
$('#CompanyModal').html("Add Company");
$('#company-modal').modal('show');
$('#id').val('');
}
function editFunc(id){
$.ajax({
type:"POST",
url: "{{ url('edit-company') }}",
data: { id: id },
dataType: 'json',
success: function(res){
$('#CompanyModal').html("Edit Company");
$('#company-modal').modal('show');
$('#id').val(res.id);
$('#name').val(res.name);
$('#address').val(res.address);
$('#email').val(res.email);
}
});
}
function deleteFunc(id){
if (confirm("Delete Record?") == true) {
var id = id;
// ajax
$.ajax({
type:"POST",
url: "{{ url('delete-company') }}",
data: { id: id },
dataType: 'json',
success: function(res){
var oTable = $('#ajax-crud-datatable').dataTable();
oTable.fnDraw(false);
}
});
}
}
$('#CompanyForm').submit(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
type:'POST',
url: "{{ url('store-company')}}",
data: formData,
cache:false,
contentType: false,
processData: false,
success: (data) => {
$("#company-modal").modal('hide');
var oTable = $('#ajax-crud-datatable').dataTable();
oTable.fnDraw(false);
$("#btn-save").html('Submit');
$("#btn-save"). attr("disabled", false);
},
error: function(data){
console.log(data);
}
});
});
</script>
</html>

Lets go to your browser and run this url

http://127.0.0.1:8000/ajax-crud-datatable

Now its open like this and successfully working and store in database as well.

Thanks 🙏🙏

Tagged : / / / /
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x