In this tutorial you will learn about the Laravel 5.8 Ajax CRUD Using Datatables and its application with practical example.
Laravel 5.8 Ajax CRUD Using Datatables
In this tutorial, you will learn to implement ajax based CRUD (Create, Read, Update and Delete) operations using datatable js. In this tutorial, we will be using yajra datatable package for listing of records with pagination, sorting and filter (search) feature.
In this step by step guide, we will be creating a simple laravel 5.8 application to demonstrate you how to install yajra datatable package and implement ajax based CRUD operations with datatable js.
Install Laravel 5.8
First of all we need to create a fresh laravel project, download and install Laravel 5.8 using the below command
1 |
composer create-project --prefer-dist laravel/laravel larablog |
Configure Database In .env file
Now, lets create a MySQL database and connect it with laravel application. After creating database we need to set database credential in application’s .env file.
.env
1 2 3 4 5 6 |
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=larablog DB_USERNAME=root DB_PASSWORD= |
Generate Application Key
Open terminal and switch to the project directory and run the following command to generate application key and configure cache.
1 |
php artisan key:generate |
1 |
php artisan config:cache |
Set Default String Length
Locate the file “app/Providers/AppServiceProvider”, and add following line of code to the top of the file
1 |
use Illuminate\Support\Facades\Schema; |
and inside the boot method set a default string length as given below –
1 |
Schema::defaultStringLength(191); |
So this is how “app/Providers/AppServiceProvider” file looks like –
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<?php namespace App\Providers; use Illuminate\Support\ServiceProvider; use Illuminate\Support\Facades\Schema; class AppServiceProvider extends ServiceProvider { public function boot() { // Schema::defaultStringLength(191); } public function register() { // } } |
Create Database Table
Now, we have to define table schema for posts table. Open terminal and let’s run the following command to generate a migration file to create posts table in our database.
1 |
php artisan make:migration create_posts_table --create=posts |
Once this command is executed you will find a migration file created under “database/migrations”. lets open migration file and put following code in it –
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreatePostsTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('posts', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('title'); $table->string('body'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('posts'); } } |
Run Migration
Now, run following command to migrate database schema.
1 |
php artisan migrate |
After, the migration executed successfully the posts table will be created in database along with migrations, password_resets and users table.
Create Model
Next, we need to create a model called Post using below command.
1 |
php artisan make:model Post |
Once, the above command is executed it will create a model file Post.php in app directory. Next, we have to assign fillable fields using fillable property inside Post.php file. Open app/Post.php file and put the following code in it –
app/Post.php
1 2 3 4 5 6 7 8 9 10 11 |
<?php namespace App; use Illuminate\Database\Eloquent\Model; class Post extends Model { // protected $fillable = [ 'title', 'body' ]; } |
Install Yajra Datatable Package
In this step, we will install Yajra Datatables Package via the composer dependency manager. Use the following command to install Yajra Datatables Package.
1 |
composer require yajra/laravel-datatables-oracle |
After Installing Yajra Datatables package, we need to add service provider and alias in config/app.php file as following.
config/app.php
1 2 3 4 5 6 7 8 9 |
'providers' => [ // Other service providers… Yajra\DataTables\DataTablesServiceProvider::class, ], 'aliases' => [ // Other aliases… 'Datatables' => Yajra\Datatables\Facades\Datatables::class, ], |
Create Controller
Next, we have to create a controller to handle Ajax CRUD Operations. Create a controller named AjaxCrudController using command given below –
1 |
php artisan make:controller dtable/AjaxCrudController |
Once the above command executed, it will create a controller file AjaxCrudController.php in app/Http/Controllers/dtable directory. Open the dtable/AjaxCrudController.php file and put the following code in it.
app/Http/Controllers/dtable/AjaxCrudController.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 |
<?php namespace App\Http\Controllers\dtable; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App\Post; use Redirect,Response; class AjaxCrudController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { if(request()->ajax()) { return datatables()->of(Post::latest()->get()) ->addColumn('action', function($data){ $button = '<a href="javascript:void(0)" data-toggle="tooltip" data-id="'.$data->id.'" data-original-title="Edit" class="edit btn btn-success edit-post">Edit</a>'; $button .= ' '; $button .= '<a href="javascript:void(0);" id="delete-post" data-toggle="tooltip" data-original-title="Delete" data-id="'.$data->id.'" class="delete btn btn-danger"> Delete</a>'; return $button; }) ->rawColumns(['action']) ->make(true); } return view('dtable.index'); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $postId = $request->post_id; $post = Post::updateOrCreate(['id' => $postId], ['title' => $request->title, 'body' => $request->body]); return Response::json($post); } /** * Show the form for editing the specified resource. * */ public function edit($id) { $where = array('id' => $id); $post = Post::where($where)->first(); return Response::json($post); } /** * Remove the specified resource from storage. * */ public function destroy($id) { $post = Post::where('id',$id)->delete(); return Response::json($post); } } |
Create Blade / View Files
In this step, we will create view/blade file to perform CRUD Operations. Lets create a blade file “index.blade.php” in “resources/views/dtable/” directory and put the following code in it respectively.
resources/views/dtable/index.blade.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 |
<!DOCTYPE html> <html lang="en"> <head> <!-- CSRF Token --> <meta name="csrf-token" content="{{ csrf_token() }}"> <title>Laravel 5.8 Ajax CRUD Using Datatables - W3Adda</title> <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"> <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> </head> <body> <div class="container"> <h2>Laravel 5.8 Ajax CRUD Using Datatables - W3Adda</h2> <br> <a href="javascript:void(0)" class="btn btn-info ml-3" id="add-new-post">Add New Post</a> <br><br> <table class="table table-bordered table-striped" id="laravel_datatable"> <thead> <tr> <th>ID</th> <th>Title</th> <th>Body</th> <th>Created at</th> <th>Action</th> </tr> </thead> </table> </div> <div class="modal fade" id="ajax-crud-modal" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title" id="postCrudModal"></h4> </div> <div class="modal-body"> <form id="postForm" name="postForm" class="form-horizontal"> <input type="hidden" name="post_id" id="post_id"> <div class="form-group"> <label for="name" class="col-sm-2 control-label">Title</label> <div class="col-sm-12"> <input type="text" class="form-control" id="title" name="title" value="" required=""> </div> </div> <div class="form-group"> <label class="col-sm-2 control-label">Body</label> <div class="col-sm-12"> <input class="form-control" id="body" name="body" value="" required=""> </div> </div> <div class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-primary" id="btn-save" value="create">Save </button> </div> </form> </div> <div class="modal-footer"> </div> </div> </div> </div> </body> </html> <script> $(document).ready( function () { $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); $('#laravel_datatable').DataTable({ processing: true, serverSide: true, ajax: { url: "{{ route('dtable-posts.index') }}", type: 'GET', }, columns: [ { data: 'id', name: 'id', 'visible': false}, { data: 'title', name: 'title' }, { data: 'body', name: 'body' }, { data: 'created_at', name: 'created_at' }, {data: 'action', name: 'action', orderable: false}, ], order: [[0, 'desc']] }); $('#add-new-post').click(function () { $('#btn-save').val("create-post"); $('#post_id').val(''); $('#postForm').trigger("reset"); $('#postCrudModal').html("Add New Post"); $('#ajax-crud-modal').modal('show'); }); $('body').on('click', '.edit-post', function () { var post_id = $(this).data('id'); $.get('dtable-posts/'+post_id+'/edit', function (data) { $('#name-error').hide(); $('#email-error').hide(); $('#postCrudModal').html("Edit Post"); $('#btn-save').val("edit-post"); $('#ajax-crud-modal').modal('show'); $('#post_id').val(data.id); $('#title').val(data.title); $('#body').val(data.body); }) }); $('body').on('click', '#delete-post', function () { var post_id = $(this).data("id"); confirm("Are You sure want to delete !"); $.ajax({ type: "get", url: "dtable-posts/destroy/"+post_id, success: function (data) { var oTable = $('#laravel_datatable').dataTable(); oTable.fnDraw(false); }, error: function (data) { console.log('Error:', data); } }); }); }); if ($("#postForm").length > 0) { $("#postForm").validate({ submitHandler: function(form) { var actionType = $('#btn-save').val(); $('#btn-save').html('Sending..'); $.ajax({ data: $('#postForm').serialize(), url: "{{ route('dtable-posts.store') }}", type: "POST", dataType: 'json', success: function (data) { $('#postForm').trigger("reset"); $('#ajax-crud-modal').modal('hide'); $('#btn-save').html('Save Changes'); var oTable = $('#laravel_datatable').dataTable(); oTable.fnDraw(false); }, error: function (data) { console.log('Error:', data); $('#btn-save').html('Save Changes'); } }); } }) } </script> |
Create Routes
After this, we need to add following routes in “routes/web.php” file along with a resource route. Lets open “routes/web.php” file and add following route.
routes/web.php
1 2 |
Route::resource('dtable-posts', 'dtable\AjaxCrudController'); Route::get('dtable-posts/destroy/{id}', 'dtable\AjaxCrudController@destroy'); |
Now we are ready to run our example so lets start the development server using following artisan command –
1 |
php artisan serve |
Now, open the following URL in browser to see the output –
http://localhost:8000/dtable-posts
Output:-
Click “Add New Post” to submit new post.
Click “Edit” button to edit corresponding post.
Click “Delete” button to delete corresponding post.