Today, We want to share with you laravel ajax crud.In this post we will show you Ajax CRUD [CReate Update Delete] with PHP Laravel and MySQL database, hear for laravel c.r.u.d. with modals & ajax we will give you demo and example for implement.In this post, we will learn about PHP Laravel MySQL CRUD Application with an example.
CRUD application in Laravel using jQuery
Add, Edit, Update, and Delete functionality is used almost every PHP Laravel application.
Install Yajra Datatable
composer require yajra/laravel-datatables-oracle
config/app.php
..... 'providers' => [ .... Yajra\DataTables\DataTablesServiceProvider::class, ] 'aliases' => [ .... 'DataTables' => Yajra\DataTables\Facades\DataTables::class, ] .....
Step 3: Database Configuration
.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)
Step 4: Create Migration Table
php artisan make:migration create_brands_table --create=brands
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateBrandsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('brands', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('name'); $table->text('information'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('brands'); } }
Step 5: Create Route
routes/web.php
Route::resource('ajaxbrands','BrandAjaxController');
Add Controller and Model
app/Http/Controllers/BrandAjaxController.php
<?php namespace App\Http\Controllers; use App\Brand; use Illuminate\Http\Request; use DataTables; class BrandAjaxController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index(Request $request) { if ($request->ajax()) { $data = Brand::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 editBrand">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 deleteBrand">Delete</a>'; return $btn; }) ->rawColumns(['action']) ->make(true); } return view('brandAjax',compact('brands')); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { Brand::updateOrCreate(['id' => $request->brand_id], ['name' => $request->name, 'information' => $request->information]); return response()->json(['success'=>'Brand saved successfully.']); } /** * Show the form for editing the specified resource. * * @param \App\Brand $brand * @return \Illuminate\Http\Response */ public function edit($id) { $brand = Brand::find($id); return response()->json($brand); } /** * Remove the specified resource from storage. * * @param \App\Brand $brand * @return \Illuminate\Http\Response */ public function destroy($id) { Brand::find($id)->delete(); return response()->json(['success'=>'Brand deleted successfully.']); } }
app/Brand.php
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Brand extends Model { protected $fillable = [ 'name', 'information' ]; }
Step 7: Add Blade Files
resources/views/brandAjax.blade.php
<!DOCTYPE html> <html> <head> <title>Laravel 6 Ajax CRUD tutorial using Datatable - Pakainfo.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"> <h2>Laravel 6 Ajax CRUD tutorial using Datatable - Pakainfo.com</h2> <a class="btn btn-success" href="javascript:void(0)" id="createNewBrand"> Create New Brand</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="brandForm" name="brandForm" class="form-horizontal"> <input type="hidden" name="brand_id" id="brand_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="Give Any 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="information" name="information" required="" placeholder="Give Any Details" class="form-control"></textarea> </div> </div> <div class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-primary" id="submitBrands" 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('ajaxbrands.index') }}", columns: [ {data: 'DT_RowIndex', name: 'DT_RowIndex'}, {data: 'name', name: 'name'}, {data: 'information', name: 'information'}, {data: 'action', name: 'action', orderable: false, searchable: false}, ] }); $('#createNewBrand').click(function () { $('#submitBrands').val("create-brand"); $('#brand_id').val(''); $('#brandForm').trigger("reset"); $('#modelHeading').html("Create New Brand"); $('#ajaxModel').modal('show'); }); $('body').on('click', '.editBrand', function () { var brand_id = $(this).data('id'); $.get("{{ route('ajaxbrands.index') }}" +'/' + brand_id +'/edit', function (data) { $('#modelHeading').html("Edit Brand"); $('#submitBrands').val("edit-user"); $('#ajaxModel').modal('show'); $('#brand_id').val(data.id); $('#name').val(data.name); $('#information').val(data.information); }) }); $('#submitBrands').click(function (e) { e.preventDefault(); $(this).html('Sending..'); $.ajax({ data: $('#brandForm').serialize(), url: "{{ route('ajaxbrands.store') }}", type: "POST", dataType: 'json', success: function (data) { $('#brandForm').trigger("reset"); $('#ajaxModel').modal('hide'); table.draw(); }, error: function (data) { console.log('Error:', data); $('#submitBrands').html('Save Changes'); } }); }); $('body').on('click', '.deleteBrand', function () { var brand_id = $(this).data("id"); confirm("Are You sure want to delete !"); $.ajax({ type: "DELETE", url: "{{ route('ajaxbrands.store') }}"+'/'+brand_id, success: function (data) { table.draw(); }, error: function (data) { console.log('Error:', data); } }); }); }); </script> </html>
I hope you get an idea about CRUD stands for Create, Read, Update and Delete database data..
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.
I am Jaydeep Gondaliya , a software engineer, the founder and the person running Pakainfo. I’m a full-stack developer, entrepreneur and owner of Pakainfo.com. I live in India and I love to write tutorials and tips that can help to other artisan, a Passionate Blogger, who love to share the informative content on PHP, JavaScript, jQuery, Laravel, CodeIgniter, VueJS, AngularJS and Bootstrap from the early stage.