Today, i will show you how to create ajax crud module with bootstrap modal & pagination in laravel 5.8. we can build ajax create read update and delete records in laravel 5.8. we will use yajra datatable to list a data on index page with sorting, pagination and searching.
I will create product module with jquery ajax crud operation in laravel 5.8. you can follow this tutorial and easily make ajax crud with your laravel 5.8 application.
Every admin panel require to create master module with laravel 5 app. but if you create with ajax and datatable library than it become awesome.
So let's follow my tutorial to create ajax crud application in laravel 5.8.
Install Laravel 5.8
first of all we need to get fresh Laravel 5.8 version application using bellow command, So open your terminal OR command prompt and run bellow command:
composer create-project --prefer-dist laravel/laravel blog
Install Yajra Datatable Package
We need to install yajra datatable composer package for datatable, so you can install using following command:
composer require yajra/laravel-datatables-oracle
After that you need to set providers and alias.
config/app.php
.....
'providers' => [
....
Yajra\DataTables\DataTablesServiceProvider::class,
]
'aliases' => [
....
'DataTables' => Yajra\DataTables\Facades\DataTables::class,
]
.....
Update Database Configuration
In second step, we will make database configuration for example database name, username, password etc for our crud application of laravel 5.8. So let's open .env file and fill all details like as bellow:
.env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=here your database name(blog)
DB_USERNAME=here database username(root)
DB_PASSWORD=here database password(root)
Create Table
we are going to create ajax crud application for product. so we have to create migration for "products" table using Laravel 5.8 php artisan command, so first fire bellow command:
php artisan make:migration create_products_table --create=products
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 products table.
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateProductsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->text('detail');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('products');
}
}
Now you have to run this migration by following command:
php artisan migrate
Create Resource Route
Here, we need to add resource route for product ajax crud application. so open your "routes/web.php" file and add following route.
routes/web.php
Route::resource('ajaxproducts','ProductAjaxController');
Create Controller and Model
In this step, now we should create new controller as ProductAjaxController. So run bellow command and create new controller.
So, let's copy bellow code and put on ProductAjaxController.php file.
app/Http/Controllers/ProductAjaxController.php
<?php
namespace App\Http\Controllers;
use App\Product;
use Illuminate\Http\Request;
use DataTables;
class ProductAjaxController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index(Request $request)
{
if ($request->ajax()) {
$data = Product::latest()->get();
return Datatables::of($data)
->addIndexColumn()
->addColumn('action', function($row){
$btn = '<a href="javascript:void(0)" data-toggle="tooltip" data-id="'.$row->id.'" data-original-title="Edit" class="edit btn btn-primary btn-sm editProduct">Edit</a>';
$btn = $btn.' <a href="javascript:void(0)" data-toggle="tooltip" data-id="'.$row->id.'" data-original-title="Delete" class="btn btn-danger btn-sm deleteProduct">Delete</a>';
return $btn;
})
->rawColumns(['action'])
->make(true);
}
return view('productAjax',compact('products'));
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
Product::updateOrCreate(['id' => $request->product_id],
['name' => $request->name, 'detail' => $request->detail]);
return response()->json(['success'=>'Product saved successfully.']);
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Product $product
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$product = Product::find($id);
return response()->json($product);
}
/**
* Remove the specified resource from storage.
*
* @param \App\Product $product
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
Product::find($id)->delete();
return response()->json(['success'=>'Product deleted successfully.']);
}
}
Here Add 10
Ok, so after run bellow command you will find "app/Product.php" and put bellow content in Product.php file:
app/Product.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
protected $fillable = [
'name', 'detail'
];
}
Create Blade Files
In last step. In this step we have to create just blade file. so we need to create only one blade file as productAjax.blade.php file.
So let's just create following file and put bellow code.
resources/views/productAjax.blade.php
<!DOCTYPE html>
<html>
<head>
<title>Laravel 5.8 Ajax CRUD tutorial using Datatable - HDTuto.com</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>
</head>
<body>
<div class="container">
<h1>Laravel 5.8 Ajax CRUD tutorial using Datatable - HDTuto.com</h1>
<a class="btn btn-success" href="javascript:void(0)" id="createNewProduct"> Create New Product</a>
<table class="table table-bordered data-table">
<thead>
<tr>
<th>No</th>
<th>Name</th>
<th>Details</th>
<th width="280px">Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<div class="modal fade" id="ajaxModel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="modelHeading"></h4>
</div>
<div class="modal-body">
<form id="productForm" name="productForm" class="form-horizontal">
<input type="hidden" name="product_id" id="product_id">
<div class="form-group">
<label for="name" class="col-sm-2 control-label">Name</label>
<div class="col-sm-12">
<input type="text" class="form-control" id="name" name="name" placeholder="Enter Name" value="" maxlength="50" required="">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">Details</label>
<div class="col-sm-12">
<textarea id="detail" name="detail" required="" placeholder="Enter Details" class="form-control"></textarea>
</div>
</div>
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-primary" id="saveBtn" value="create">Save changes
</button>
</div>
</form>
</div>
</div>
</div>
</div>
</body>
<script type="text/javascript">
$(function () {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var table = $('.data-table').DataTable({
processing: true,
serverSide: true,
ajax: "{{ route('ajaxproducts.index') }}",
columns: [
{data: 'DT_RowIndex', name: 'DT_RowIndex'},
{data: 'name', name: 'name'},
{data: 'detail', name: 'detail'},
{data: 'action', name: 'action', orderable: false, searchable: false},
]
});
$('#createNewProduct').click(function () {
$('#saveBtn').val("create-product");
$('#product_id').val('');
$('#productForm').trigger("reset");
$('#modelHeading').html("Create New Product");
$('#ajaxModel').modal('show');
});
$('body').on('click', '.editProduct', function () {
var product_id = $(this).data('id');
$.get("{{ route('ajaxproducts.index') }}" +'/' + product_id +'/edit', function (data) {
$('#modelHeading').html("Edit Product");
$('#saveBtn').val("edit-user");
$('#ajaxModel').modal('show');
$('#product_id').val(data.id);
$('#name').val(data.name);
$('#detail').val(data.detail);
})
});
$('#saveBtn').click(function (e) {
e.preventDefault();
$(this).html('Sending..');
$.ajax({
data: $('#productForm').serialize(),
url: "{{ route('ajaxproducts.store') }}",
type: "POST",
dataType: 'json',
success: function (data) {
$('#productForm').trigger("reset");
$('#ajaxModel').modal('hide');
table.draw();
},
error: function (data) {
console.log('Error:', data);
$('#saveBtn').html('Save Changes');
}
});
});
$('body').on('click', '.deleteProduct', function () {
var product_id = $(this).data("id");
confirm("Are You sure want to delete !");
$.ajax({
type: "DELETE",
url: "{{ route('ajaxproducts.store') }}"+'/'+product_id,
success: function (data) {
table.draw();
},
error: function (data) {
console.log('Error:', data);
}
});
});
});
</script>
</html>
Now you can test it.
I hope you found your best...
Do you like below Tutorials ?
- Laravel 5.6 - Collection could not be converted to int
- Laravel - How to generate secure https URL from route?
- Laravel - Vue JS File Upload Example
- How to get last 7 days data in Laravel?
- Laravel Validation required if other field empty example
- Laravel Eloquent - When Case Statement in Select Query Example
- Laravel 7.x and 6.x Passing Variable to Javascript Example
- How to pass PHP variables in JavaScript or jQuery?